package com.css.fxfzdzzh.modules.sandLiquefaction.service.impl;

import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzdzzh.base.annotation.AddData;
import com.css.fxfzdzzh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.constants.RedisKeyConstants;
import com.css.fxfzdzzh.constants.YNEnum;
import com.css.fxfzdzzh.enums.OperandsEnum;
import com.css.fxfzdzzh.enums.ResultEnum;
import com.css.fxfzdzzh.enums.SandLiqueFactionEnum;
import com.css.fxfzdzzh.modules.basicData.entity.SysDataVersion;
import com.css.fxfzdzzh.modules.basicData.service.impl.SysDataVersionService;
import com.css.fxfzdzzh.modules.drill.service.DrillService;
import com.css.fxfzdzzh.modules.eqLandslide.count.entity.*;
import com.css.fxfzdzzh.modules.eqLandslide.count.param.TaskModelParam;
import com.css.fxfzdzzh.modules.eqLandslide.count.repository.EqLandslideRepository;
import com.css.fxfzdzzh.modules.eqLandslide.count.service.EqLandslideService;
import com.css.fxfzdzzh.modules.eqLandslide.lawAnalysis.repository.LawAnalysisRepository;
import com.css.fxfzdzzh.modules.eqLandslide.lawAnalysis.vo.BufferAreaVO;
import com.css.fxfzdzzh.modules.grid.entity.DistrictBoundary;
import com.css.fxfzdzzh.modules.hypergraph.service.HypergraphService;
import com.css.fxfzdzzh.modules.sandLiquefaction.entity.*;
import com.css.fxfzdzzh.modules.sandLiquefaction.param.EvaluateParam;
import com.css.fxfzdzzh.modules.sandLiquefaction.repository.SandLiquefactionRepository;
import com.css.fxfzdzzh.modules.sandLiquefaction.service.SandLiquefactionService;
import com.css.fxfzdzzh.modules.sandLiquefaction.vo.*;
import com.css.fxfzdzzh.modules.spatialData.service.BoundaryService;
import com.css.fxfzdzzh.modules.taskManage.entity.TaskEntity;
import com.css.fxfzdzzh.modules.taskManage.repository.TaskRepository;
import com.css.fxfzdzzh.modules.taskManage.service.TaskService;
import com.css.fxfzdzzh.modules.tifData.service.ElevationMapService;
import com.css.fxfzdzzh.util.*;
import com.css.fxfzdzzh.web.PlatformSessionContext;
import com.css.fxfzdzzh.zcpt.sys.entity.SUser;
import com.css.fxfzdzzh.zcpt.sys.service.SUserService;
import com.css.fxfzdzzh.zcpt.sys.service.SysAreaService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.apache.xpath.operations.Bool;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.util.GeometricShapeFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author Dbj
 * @date 2023年03月11日  11:10
 */
@Service
public class SandLiquefactionServiceImpl implements SandLiquefactionService {

    @Resource
    @Qualifier("myTaskExecutor")
    private Executor executor;

    @Resource
    SandLiquefactionRepository sandLiquefactionRepository;

    @Value("${basicData.url}")
    public String basicDataUrl;

    @Resource
    DrillService drillService;

    @Resource
    RedisTemplate redisTemplate;
    @Resource
    RestTemplate restTemplate;

    @Resource
    SUserService sUserService;

    @Resource
    TaskService taskService;
    @Resource
    TaskRepository taskRepository;


    @Resource
    LawAnalysisRepository lawAnalysisRepository;

    @Resource
    BoundaryService boundaryService;
    @Resource
    HypergraphService hypergraphService;
    @Resource
    SysDataVersionService sysDataVersionService;
    @Resource
    SysAreaService sysAreaService;
    @Resource
    EqLandslideRepository eqLandslideRepository;
    @Resource
    ElevationMapService elevationMapService;
    @Resource
    EqLandslideService eqLandslideService;
    @Resource
    JdbcTemplate jdbcTemplate;
    /**
     * 数据源
     * 10.19.41.111
     */
    @Value("${spring.datasource.url}")
    private String url = "";
    @Value("${spring.datasource.username}")
    private String name = "";
    @Value("${spring.datasource.password}")
    private String pwd = "";

    //椭圆--地震影响场
    /**
     * 定义地球半径（米）
     */
    private final double R_EARTH = 6378137;

    /**
     * 定义地球赤道周长（米）
     */
    private final double P_EARTH = 2 * Math.PI * R_EARTH;


    @Override
    public Map<String, Object> getModelSandLiquefaction(TaskModelParam param, int curPage, int pageSize) {
        return sandLiquefactionRepository.getPage(param, curPage, pageSize);
    }

    @Override
    public DzzhModelResultVO getFinalResult(String taskId, String algorithmType) throws IllegalAccessException {
        TaskEntity taskEntity = taskService.getTaskWithOutGeom(taskId);
        DzzhModelResultVO vo = new DzzhModelResultVO();
        DzzhModelSandLiquefaction modelSandLiquefaction = sandLiquefactionRepository.getModelSandLiquefaction(taskId, ResultEnum.FINA.getState() + "");
        if (PlatformObjectUtils.isEmpty(modelSandLiquefaction) || ObjectUtils.isEmpty(modelSandLiquefaction)) {
            modelSandLiquefaction = new DzzhModelSandLiquefaction();
            modelSandLiquefaction.setTaskNum(taskEntity.getTaskNum()).setDisasterType("砂土液化").setTaskDistrict(taskEntity.getTaskDistrict()).setTaskId(taskEntity.getDtId());
            String userID = PlatformSessionContext.getUserID();
            String user = sUserService.getSUser(userID);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            modelSandLiquefaction.setEvaluateUserName(sUser.getUserName());
            modelSandLiquefaction.setEvaluateUser(userID);
            vo.setModelSandLiquefaction(modelSandLiquefaction);
            vo.setResultSandLiquefaction(new ArrayList<>());
            return vo;
        } else {
            modelSandLiquefaction.setTaskNum(taskEntity.getTaskNum()).setDisasterType("砂土液化").setTaskDistrict(taskEntity.getTaskDistrict()).setTaskId(taskEntity.getDtId());
            vo.setModelSandLiquefaction(modelSandLiquefaction);
            if (!"3".equals(algorithmType)) {
                List<DzzhResultSandLiquefaction> list = sandLiquefactionRepository.getDataById(modelSandLiquefaction.getDmslId());
                List<DzzhResultSandLiquefactionVO> voList = new ArrayList<>();
                if (PlatformObjectUtils.isNotEmpty(list)) {
                    Map<BigDecimal, List<DzzhResultSandLiquefaction>> collect = list.stream().collect(Collectors.groupingBy(dzzhResultSandLiquefaction -> dzzhResultSandLiquefaction.getEarthquakeAcceleration()));
                    List<DzzhResultSandLiquefactionVO> finalVoList = voList;
                    collect.forEach((k, v)->{
                        if(v.size()>0){
                            DzzhResultSandLiquefactionVO dzzhResultSandLiquefactionVO = new DzzhResultSandLiquefactionVO();
                            dzzhResultSandLiquefactionVO.setEarthquakeAcceleration(k);
                            dzzhResultSandLiquefactionVO.setLiquefactionGroundWaterDepth("实际水位深度");
                            dzzhResultSandLiquefactionVO.setCanShow("1");
                            finalVoList.add(dzzhResultSandLiquefactionVO);
                        }
                        DzzhResultSandLiquefactionVO dzzhResultSandLiquefactionVO = new DzzhResultSandLiquefactionVO();
                        dzzhResultSandLiquefactionVO.setEarthquakeAcceleration(k);
                        dzzhResultSandLiquefactionVO.setLiquefactionGroundWaterDepth("0");
                        dzzhResultSandLiquefactionVO.setCanShow("1");
                        finalVoList.add(dzzhResultSandLiquefactionVO);
                    });
                    voList = finalVoList.stream().sorted(Comparator.comparing(DzzhResultSandLiquefactionVO::getEarthquakeAcceleration)).collect(Collectors.toList());
                    vo.setResultSandLiquefaction(voList);
                }
                List<DzzhResultSandLiquefactionVO> evaluateResult = getEvaluateResult(modelSandLiquefaction.getDmslId(), taskEntity.getTaskDistrict(), taskId);
                vo.setResultSandLiquefaction(evaluateResult);
            }
        }


//        else {
//            AhpRatio ahpRatio = sandLiquefactionRepository.getAhpRatioData(taskId, modelSandLiquefaction.getDmslId());
//            Ahp ahp = new Ahp();
//            if (ahpRatio != null) {
//                String ratio = ahpRatio.getRatio();
//                JSONObject parse = (JSONObject) JSONObject.parse(ratio);
//                Field[] fields = ahp.getClass().getDeclaredFields();
//                if (PlatformObjectUtils.isNotEmpty(fields)) {
//                    for (Field field : fields) {
//                        field.setAccessible(true);
//                        AddData annotation = field.getAnnotation(AddData.class);
//                        if (annotation == null) {
//                            continue;
//                        }
//                        String name = field.getName();
//                        BigDecimal value = parse.getBigDecimal(name);
//                        if (PlatformObjectUtils.isNotEmpty(value)) {
//                            field.set(ahp, value);
//                        }
//                    }
//                }
//            }
//            vo.setAhp(ahp);
//        }
        return vo;
    }

    @Override
    public DzzhModelAhpVO getAhpFinalResult(String taskId) throws IllegalAccessException {
        TaskEntity taskEntity = taskService.viewTask(taskId);
        DzzhModelAhpVO vo = new DzzhModelAhpVO();
        DzzhModelSandLiquefaction modelSandLiquefaction = sandLiquefactionRepository.getModelSandLiquefaction1(taskId, ResultEnum.FINA.getState() + "","3");
        if (PlatformObjectUtils.isEmpty(modelSandLiquefaction) || ObjectUtils.isEmpty(modelSandLiquefaction)) {
            modelSandLiquefaction = new DzzhModelSandLiquefaction();
            modelSandLiquefaction.setTaskNum(taskEntity.getTaskNum()).setDisasterType("砂土液化").setTaskDistrict(taskEntity.getTaskDistrict()).setTaskId(taskEntity.getDtId());
            String userID = PlatformSessionContext.getUserID();
            String user = sUserService.getSUser(userID);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            modelSandLiquefaction.setEvaluateUserName(sUser.getUserName());
            modelSandLiquefaction.setEvaluateUser(userID);
            vo.setModelSandLiquefaction(modelSandLiquefaction);
            vo.setAhpRatioVO(new AhpRatioVO());
            return vo;
        } else {
            modelSandLiquefaction.setTaskNum(taskEntity.getTaskNum()).setDisasterType("砂土液化").setTaskDistrict(taskEntity.getTaskDistrict()).setTaskId(taskEntity.getDtId());
            //查看是否生成过地形指数、场地类别和评估结果
            DzzhDtis mapResult = sandLiquefactionRepository.getMapResultFile(taskId,modelSandLiquefaction.getDmslId());
            modelSandLiquefaction.setStatus1(StringUtils.isNotBlank(mapResult.getZhdxzs())?"1":"0");
            modelSandLiquefaction.setStatus2(StringUtils.isNotBlank(mapResult.getCdlb1()) && StringUtils.isNotBlank(mapResult.getCdlb2())?"1":"0");
            Integer num = sandLiquefactionRepository.hasAhpResult(modelSandLiquefaction.getDmslId());
            modelSandLiquefaction.setStatus3(num!=null&&num>0?"1":"0");
            OmprehensiveTerrainIndexAndSite data = sandLiquefactionRepository.getOmprehensiveTerrainIndexAndSiteByDmslId(modelSandLiquefaction.getDmslId());
            if(data!=null){
                modelSandLiquefaction.setLandFormFileName(data.getZhdxzs());
                List<String> list = new ArrayList<>();
                list.add(data.getCdlb1());
                list.add(data.getCdlb2());
                modelSandLiquefaction.setSiteFileName(list);
            }
            vo.setModelSandLiquefaction(modelSandLiquefaction);
            AhpRatioVO ahpVO = new AhpRatioVO();
            AhpRatio ahpRatio = sandLiquefactionRepository.getAhpRatioData(taskId, modelSandLiquefaction.getDmslId());
            if (ahpRatio != null) {
                String ratio = ahpRatio.getRatio();
                JSONObject parse = (JSONObject) JSONObject.parse(ratio);
                Field[] fields = ahpVO.getClass().getDeclaredFields();
                if (PlatformObjectUtils.isNotEmpty(fields)) {
                    for (Field field : fields) {
                        field.setAccessible(true);
                        AddData annotation = field.getAnnotation(AddData.class);
                        if (annotation == null) {
                            continue;
                        }
                        String name = field.getName();
                        BigDecimal value = parse.getBigDecimal(name);
                        if (PlatformObjectUtils.isNotEmpty(value)) {
                            field.set(ahpVO, value);
                        }
                    }
                }
            }
            vo.setAhpRatioVO(ahpVO);
        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveToCenterResult(String taskId, String algorithmType) {
        DzzhModelSandLiquefaction modelSandLiquefaction = sandLiquefactionRepository.getModelSandLiquefaction(taskId, ResultEnum.FINA.getState() + "");
        if (PlatformObjectUtils.isNotEmpty(modelSandLiquefaction)) {
            String userID = PlatformSessionContext.getUserID();
            String user = sUserService.getSUser(userID);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            DzzhModelSandLiquefaction temp = new DzzhModelSandLiquefaction();
            BeanUtils.copyProperties(modelSandLiquefaction, temp);
            String dmslId = UUIDGenerator.getUUID();
            temp.setDmslId(dmslId);
            temp.setResultStatus(ResultEnum.CENTER.getState() + "");
            temp.setCreateTime(new Date());
            temp.setCreateUser(userID);
            temp.setCreateUserName(sUser.getUserName());
            temp.setUpdateTime(new Date());
            temp.setDataFrom(modelSandLiquefaction.getDataFrom());
            sandLiquefactionRepository.saveToCenterResult(temp);
            //模型数据保存为中间结果
            if (!"3".equals(algorithmType)) {
                List<DzzhResultDetailSandLiquefaction> resultSandLiquefactionList = sandLiquefactionRepository.getResultDetailSandLiquefactionList(modelSandLiquefaction.getDmslId());
                List<DzzhResultDetailSandLiquefaction> list = new ArrayList<>(resultSandLiquefactionList.size());
                if (PlatformObjectUtils.isNotEmpty(resultSandLiquefactionList)) {
                    resultSandLiquefactionList.forEach(entity -> {
                        DzzhResultDetailSandLiquefaction newData = new DzzhResultDetailSandLiquefaction();
                        BeanUtils.copyProperties(entity, newData);
                        newData.setDmslId(dmslId);
                        newData.setDrslId(UUIDGenerator.getUUID());
                        list.add(newData);
                    });
                    //将非层次分析法的评估结果数据保存为中间结果
                    sandLiquefactionRepository.saveResultDetailSandLiquefaction(list);
                }
            } else {
//                List<AhpResultEntity> ahpResultList = sandLiquefactionRepository.getAhpResultList(modelSandLiquefaction.getDmslId());
                List<AhpResultEntity> ahpResultList = sandLiquefactionRepository.getAhpResultListByTaskId(modelSandLiquefaction.getDmslId(),taskId);
                List<AhpResultEntity> list = new ArrayList<>(ahpResultList.size());
                if (PlatformObjectUtils.isNotEmpty(ahpResultList)) {
                    ahpResultList.forEach(entity -> {
                        AhpResultEntity newData = AhpResultEntity.builder().build();
                        BeanUtils.copyProperties(entity, newData);
                        newData.setDmslId(dmslId);
                        newData.setDiaId(UUIDGenerator.getUUID());
                        list.add(newData);
                    });
                    //将层次分析法的评估结果保存为中间结果
                    sandLiquefactionRepository.batchSave(list);
                }

                //保存层次分析法所选的参数拷贝为中间结果
                AhpRatio ahpRatioData = sandLiquefactionRepository.getAhpRatioData(taskId, modelSandLiquefaction.getDmslId());
                if(PlatformObjectUtils.isNotEmpty(ahpRatioData)){
                    sandLiquefactionRepository.saveRatio(UUIDGenerator.getUUID(),taskId,dmslId,ahpRatioData.getRatio());
                }
                //保存层次分析法生成的超图文件保存为中间结果
                //根据任务查询
                OmprehensiveTerrainIndexAndSite obj = sandLiquefactionRepository.getOmprehensiveTerrainIndexAndSite(taskId,modelSandLiquefaction.getDmslId());
                if(PlatformObjectUtils.isNotEmpty(obj)){
                    if(PlatformObjectUtils.isEmpty(obj.getZhdxzs())){
                        obj.setZhdxzs("");
                    }
                    if(PlatformObjectUtils.isEmpty(obj.getCdlb1())){
                        obj.setCdlb1("");
                    }
                    if(PlatformObjectUtils.isEmpty(obj.getCdlb2())){
                        obj.setCdlb2("");
                    }
                    sandLiquefactionRepository.saveDtis(UUIDGenerator.getUUID(),taskId,obj.getZhdxzs(),obj.getCdlb1(),obj.getCdlb2(),obj.getGcFileName(),dmslId);
                }
                //保存层次分析法最终的评估计算超图文件为中间结果
//                List<AhpResultEntity> ahpResults = sandLiquefactionRepository.getAhpResultList(modelSandLiquefaction.getDmslId());
                List<AhpResultEntity> ahpResults = sandLiquefactionRepository.getAhpResultListByTaskId(modelSandLiquefaction.getDmslId(),taskId);
                if(PlatformObjectUtils.isNotEmpty(ahpResults) && ahpResults.size()>0){
                    for (AhpResultEntity ahpResult : ahpResults) {
                        ahpResult.setDmslId(dmslId);
                        ahpResult.setDiaId(UUIDGenerator.getUUID());
                        ahpResult.setCreateTime(new Date());
                    }
                    sandLiquefactionRepository.batchSave(ahpResults);
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delResult(String dmslId) {
        //删除模型数据
        sandLiquefactionRepository.delResult(dmslId);
        //删除层次分析法最终生成的评估结果
        sandLiquefactionRepository.deleteAhpResult(dmslId);
        //删除层次分析法自定义的参数
        sandLiquefactionRepository.deleteAhpRatio(dmslId);
        //删除评估结果
        sandLiquefactionRepository.deleteDzzhSandLiquefactionResult(dmslId);
        //删除dtis
        sandLiquefactionRepository.delDtis(dmslId);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void replaceToFinalResult(String dmslId, String flag, String taskId) {
        DzzhModelSandLiquefaction modelSandLiquefaction = sandLiquefactionRepository.getModelSandLiquefaction(taskId, ResultEnum.FINA.getState() + "");
        String userId = PlatformSessionUtils.getUserId();
        if ("1".equals(flag)) {
            //替换
            sandLiquefactionRepository.replaceToFinalResult(modelSandLiquefaction.getDmslId(), ResultEnum.CENTER.getState(), userId);
        } else {
            //sandLiquefactionRepository.delResult(modelSandLiquefaction.getDmslId());
            this.delResult(modelSandLiquefaction.getDmslId());
        }
        sandLiquefactionRepository.replaceToFinalResult(dmslId, ResultEnum.FINA.getState(), userId);
    }
    //查询钻孔信息保存到redis中
    private Map<String, Object>  setRedis(String versionCode, String taskId){
        Map<String, Object> drillMap = new HashMap<>();
        //获取主表02
        String url = basicDataUrl + "/datacenter/jcRfcpY02/getByDataVersion/" + versionCode;
        RestResponse jcsj02 = drillService.getJCSJ(url, 3);
        JSONObject para = JSONObject.parseObject(JSON.toJSONString(jcsj02));
        JSONArray jsonArray = JSON.parseArray(para.getString("data").toString());
        if(PlatformObjectUtils.isNotEmpty(jsonArray) && jsonArray.size()>0 ){
            //先删除
            redisTemplate.delete(RedisKeyConstants.SYSTEMPREFIX  + ":drill:02:"+ taskId + ":" + versionCode);
            List<JSONObject> list = JSONObject.parseArray(jsonArray.toJSONString(),JSONObject.class);
            redisTemplate.opsForList().rightPushAll(RedisKeyConstants.SYSTEMPREFIX  + ":drill:02:"+ taskId + ":" + versionCode , list);
            drillMap.put("02", jsonArray);
            jsonArray.forEach(obj->{
                JSONObject jsonObj = (JSONObject) obj;
                String id = jsonObj.getString("id");
                //查询04，05,10子表的数据
                Map<String, Map<String, String>> map = new HashMap<>(3);
                Map<String, String> cmap = new HashMap<>();
                String condition = "assise_code,bottom_depth,layer_thickness,geotechnical_name";
                cmap.put("jc_rfcp_y04", condition);
                map.put("JcRfcpY04", cmap);
                condition = "standard_start_depth,standard_end_depth,standard_number";
                cmap = new HashMap<>();
                cmap.put("jc_rfcp_y05", condition);
                map.put("JcRfcpY05", cmap);
                condition = "particle_cosmid005";
                cmap = new HashMap<>();
                cmap.put("jc_rfcp_y10", condition);
                map.put("JcRfcpY10", cmap);
                String json = JSON.toJSONString(map);
                //根据主表id查询各个子表的数据进行缓存
                String UrlPath = basicDataUrl + "/datacenter/jcRfcpY02/getSandLiquefactionZkInfo?drillId=" + id + "&paraMap={json}";
                RestResponse result = this.getJCSJ(UrlPath, 2, json);
                Map<String, List<Map<String, Object>>> data = (Map<String, List<Map<String, Object>>>) result.getData();
                data.forEach((k, v) -> {
                    redisTemplate.delete(RedisKeyConstants.SYSTEMPREFIX  + ":drill:" + taskId + ":" + versionCode + ":" + id+ ":" + k);
                    redisTemplate.opsForList().rightPushAll(RedisKeyConstants.SYSTEMPREFIX + ":drill:"  + taskId + ":" + versionCode + ":" + id+ ":" + k, v);
                    drillMap.put(RedisKeyConstants.SYSTEMPREFIX + ":drill:" + taskId + ":" + versionCode + ":" + id+ ":" + k, v);
                });
            });
        }
        return drillMap;
    }
    @Override
    public RestResponse chooseDrillData(String versionCode, String taskId) {
        this.setRedis(versionCode,taskId);
        return ResponseCreator.createSuccessResponse(versionCode);
    }

    public RestResponse getJCSJ(String url, int tab, String json) {
        MultiValueMap<String, Object> valueMap = new LinkedMultiValueMap<>();
        // String url = SJXTRESTURL + "/datacenter/jcRfcpY02/page?param=" + param;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "fxfzdzzh");
        headers.set("subsystemCode", "dzdzzhpg");
        HttpEntity<MultiValueMap> r = new HttpEntity<>(valueMap, headers);
        RestResponse resp = null;
        try {
            if (tab == 1) {
                JSONObject data = restTemplate.exchange(url, HttpMethod.POST, r, JSONObject.class).getBody().getJSONObject("data");
                resp = RestResponse.succeed(data);
            } else if (tab == 2) {
                JSONObject data = restTemplate.exchange(url, HttpMethod.GET, r, JSONObject.class, json).getBody().getJSONObject("data");
                resp = RestResponse.succeed(data);
            } else if (tab == 3) {
                JSONArray data = restTemplate.exchange(url, HttpMethod.GET, r, JSONObject.class).getBody().getJSONArray("data");
                resp = RestResponse.succeed(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resp;
    }

    /**
     * 标贯法和液化指数法的计算
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String evaluate(EvaluateParam param) throws ExecutionException, InterruptedException {
        //model表主键
        // 当为标贯法的饱和砂土或粉土时需要判断展示评估结果处的查看地图展示按钮是否显示 只做按钮是否显示的判断条件
        String canShow = "1";
        String dmslId = param.getDmslId();

        if(PlatformObjectUtils.isEmpty(dmslId)){
            //dmslId为空时表示标贯法没有参与评估计算 也就不需要删除
            dmslId = UUIDGenerator.getUUID();
        }else{
            sandLiquefactionRepository.delResult(dmslId);
            sandLiquefactionRepository.deleteDzzhSandLiquefactionResult(dmslId);
        }
        //保存模型数据
        saveResult(param, dmslId, canShow);
        //保存评估结果
        getAndSaveByModelType(dmslId, param);
        //当业务处理完成后删除保存在redis中的数据，起到为key设置生命周期的作用
        //删除钻孔子表
        Set<String> keys = redisTemplate.keys(RedisKeyConstants.SYSTEMPREFIX  + ":drill:" + param.getTaskId() + ":" + param.getVersionCode() + "*");
        redisTemplate.delete(keys);
        redisTemplate.delete(RedisKeyConstants.SYSTEMPREFIX  + ":drill:02"+ param.getTaskId() + ":" + param.getVersionCode());
        return dmslId;
    }

    /**
     * @param ahp
     * @author Dongbj
     * @date 2023/3/23 13:45
     * @desc 层次分析法计算
     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void evaluate1(Ahp ahp) throws Exception {
//        TaskEntity taskEntity = taskService.viewTask(ahp.getTaskId());
//        //先删除后保存最终结果
//        //model表主键
//        String dmslId = deleteAndSaveFinalResult(ahp);
//        //汇总权重数据
//        Map<String, List<BigDecimal>> parameter = getRatio(ahp, dmslId);
//        long currTime = System.currentTimeMillis();
//        //任务转栅格获取生成在磁盘上的栅格文件
//        CompletableFuture<String> completableFuture1 = CompletableFuture.supplyAsync(() -> {
//            String taskResultLayerName= "";
//            try {
//                taskResultLayerName = getGridFile(taskEntity.getTaskNum(),"1","dzzh_task","SmUserID","dt_id",ahp.getTaskId(),"任务");
//            } catch (Exception e) {
//                throw new RuntimeException(e.getMessage());
//            }
//            System.out.println("任务转栅格获取生成在磁盘上的栅格文件获取成功！");
//            return taskResultLayerName;
//        }, executor);
//        //地层岩性转栅格获取生成在磁盘上的栅格文件
//        //地层岩性矢量转栅格并获取文件信息
//        CompletableFuture<String> completableFuture2 = CompletableFuture.supplyAsync(() -> {
//            String lithologyVersion = ahp.getLithologyVersion();
//            String lithologyResultLayerName= "";
//            try {
//                lithologyResultLayerName = getGridFile(taskEntity.getTaskNum(),"2","jc_stratum_lithology","values1","data_version",lithologyVersion,"地层岩性");
//                System.out.println(lithologyVersion + "版本的地层岩性:{}" + lithologyResultLayerName + "解析成功！");
//            } catch (Exception e) {
//                throw new RuntimeException(e.getMessage());
//            }
//            return lithologyResultLayerName;
//        }, executor);
//        //将动峰加速度转栅格并获取文件信息
//        CompletableFuture<String> completableFuture3 = CompletableFuture.supplyAsync(() -> {
//            String pga02yResultLayerName= "";
//            try {
//                pga02yResultLayerName = getGridFile(taskEntity.getTaskNum(),"2","jc_pga_002","year50_pro_exceedance002","data_version",ahp.getA1Version(),"50年超越概率2%的地震峰值加速度数据");
//                System.out.println(ahp.getA1Version() + "版本的地震峰值加速度（2%）:{}" + pga02yResultLayerName + "解析成功！");
//            } catch (Exception e) {
//                throw new RuntimeException(e.getMessage());
//            }
//            return pga02yResultLayerName;
//        }, executor);
//        CompletableFuture<String> completableFuture4 = CompletableFuture.supplyAsync(() -> {
//            String pga10yResultLayerName= "";
//            try {
//                pga10yResultLayerName = getGridFile(taskEntity.getTaskNum(),"2","jc_pga_010","year50_pro_exceedance_010","data_version",ahp.getA2Version(),"50年超越概率10%的地震峰值加速度数据");
//                System.out.println(ahp.getA2Version() + "版本的地震峰值加速度（10%）:{}" + pga10yResultLayerName + "解析成功！");
//            } catch (Exception e) {
//                throw new RuntimeException(e.getMessage());
//            }
//            return pga10yResultLayerName;
//        }, executor);
//
//        CompletableFuture<String> completableFuture5 = CompletableFuture.supplyAsync(() -> {
//            String pga63yResultLayerName= "";
//            try {
//                pga63yResultLayerName = getGridFile(taskEntity.getTaskNum(),"2","jc_pga_063","year50_pro_exceedance_063","data_version",ahp.getA3Version(),"50年超越概率63%的地震峰值加速度数据");
//                System.out.println(ahp.getA3Version() + "版本的地震峰值加速度（63%）:{}" + pga63yResultLayerName + "解析成功！");
//            } catch (Exception e) {
//                throw new RuntimeException(e.getMessage());
//            }
//            return pga63yResultLayerName;
//        }, executor);
//        //水系
//        CompletableFuture<String> completableFuture6 = CompletableFuture.supplyAsync(() -> {
//            String waterName= "";
//            try {
//                waterName = getAndBufferWater(taskEntity,parameter.get("距河流距离"));
//            } catch (Exception e) {
//                throw new RuntimeException(e.getMessage());
//            }
//            return waterName;
//        }, executor);
//        CompletableFuture<Void> allCompletableFuture = CompletableFuture.allOf(completableFuture6, completableFuture5, completableFuture4, completableFuture3, completableFuture2, completableFuture1).whenComplete((v, th) -> {
//            Map<String, Object> paramMap = new HashMap<>();
//            paramMap.put("entity", ahp);
//            //获取场地类别-活动构造区
//            if(PlatformObjectUtils.isEmpty(ahp.getSiteFileName().get(0))){
//                throw new RuntimeException("获取场地类别-活动构造区失败");
//            }
//            paramMap.put("activeSiteName", ahp.getSiteFileName().get(0));
//            //获取场地类别-稳定构造区
//            if(PlatformObjectUtils.isEmpty(ahp.getSiteFileName().get(1))){
//                throw new RuntimeException("获取场地类别-稳定构造区失败");
//            }
//            paramMap.put("steadySiteName", ahp.getSiteFileName().get(1));
//            //综合地形指数栅格文件
//            String ctResultLayerName = ahp.getLandFormFileName();
//            paramMap.put("ctResultLayerName", ctResultLayerName);
//            try {
//                if(PlatformObjectUtils.isEmpty(completableFuture1.get())){
//                    throw new RuntimeException("任务转栅格失败");
//                }
//                paramMap.put("taskResultLayerName", completableFuture1.get());
//            } catch (InterruptedException | ExecutionException e) {
//                throw new RuntimeException("任务转栅格失败");
//            }
//            try {
//                if(PlatformObjectUtils.isEmpty(completableFuture2.get())){
//                    throw new RuntimeException("地层岩性矢量转栅格失败");
//                }
//                paramMap.put("lithologyResultLayerName", completableFuture2.get());
//            } catch (InterruptedException | ExecutionException e) {
//                throw new RuntimeException("地层岩性矢量转栅格失败");
//            }
//            try {
//                if(PlatformObjectUtils.isEmpty(completableFuture3.get())){
//                    throw new RuntimeException("动峰加速度002转栅格失败");
//                }
//                paramMap.put("pga02yResultLayerName", completableFuture3.get());
//            } catch (InterruptedException | ExecutionException e) {
//                throw new RuntimeException("动峰加速度002转栅格失败");
//            }
//            try {
//                if(PlatformObjectUtils.isEmpty(completableFuture4.get())){
//                    throw new RuntimeException("动峰加速度010转栅格失败");
//                }
//                paramMap.put("pga10yResultLayerName", completableFuture4.get());
//            } catch (InterruptedException | ExecutionException e) {
//                throw new RuntimeException("动峰加速度010转栅格失败");
//            }
//            try {
//                if(PlatformObjectUtils.isEmpty(completableFuture5.get())){
//                    throw new RuntimeException("动峰加速度063转栅格失败");
//                }
//                paramMap.put("pga63yResultLayerName", completableFuture5.get());
//            } catch (InterruptedException | ExecutionException e) {
//                throw new RuntimeException("动峰加速度063转栅格失败");
//            }
//            try {
//                if(PlatformObjectUtils.isEmpty(completableFuture6.get())){
//                    throw new RuntimeException("水系获取失败");
//                }
//                paramMap.put("waterName", completableFuture6.get());
//            } catch (InterruptedException | ExecutionException e) {
//                throw new RuntimeException("水系获取失败");
//            }
//            RestResponse restResponse = null;
//            try {
//                restResponse = getData(paramMap, parameter);
//            } catch (Exception e) {
//               throw new RuntimeException(e.getMessage());
//            }
//            if (restResponse.getCode() != 200) {
//                throw new RuntimeException("评估计算失败");
//            }
//            JSONArray jsonArray = JSON.parseObject(restResponse.getData().toString()).getJSONArray("resultLayerName");
//            List<AhpResultEntity> ahpResultEntityList = new ArrayList<>();
//            for (int i = 0; i < jsonArray.size(); i++) {
//                String fileName = jsonArray.getString(i);
//                //根据重分类的自然分割法，获取液化危害指数划分
//                String reclassifyFileName = getGridFile("reclassify", fileName, "");
//                AhpResultEntity ahpResultEntity = AhpResultEntity.builder().build();
//                ahpResultEntity.setDiaId(UUIDGenerator.getUUID());
//                //String resultLayerName = resultLayerName1 + "_计算_" + currTime + "_" + 动峰加速度+"_"+场地类别;
//                //动峰加速度
//                String pga = fileName.split("_")[fileName.split("_").length - 2];
//                //场地类别
//                String site = fileName.split("_")[fileName.split("_").length - 1];
//                if ("1".equals(pga)) {
//                    ahpResultEntity.setPga("50年超越概率2%");
//                } else if ("2".equals(pga)) {
//                    ahpResultEntity.setPga("50年超越概率10%");
//                } else {
//                    ahpResultEntity.setPga("50年超越概率63%");
//                }
//                if ("1".equals(site)) {
//                    ahpResultEntity.setPlaceType("活动构造区");
//                } else if ("2".equals(site)) {
//                    ahpResultEntity.setPlaceType("稳定大陆区");
//                }
//                ahpResultEntity.setFilePath(reclassifyFileName);
//                ahpResultEntity.setTaskId(ahp.getTaskId());
//                ahpResultEntity.setDmslId(dmslId);
//                ahpResultEntity.setCreateTime(new Date());
//                ahpResultEntity.setUserId("123");
//                ahpResultEntityList.add(ahpResultEntity);
//            }
//            if (ahpResultEntityList.size() > 0) {
//                sandLiquefactionRepository.batchSave(ahpResultEntityList);
//            }
//        });
//        try {
//            allCompletableFuture.join();
//        }catch (Exception ex){
//            throw new RuntimeException("无法获取数据文件，评估计算失败");
//        }
//    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void evaluate1(Ahp ahp) throws Exception {
        TaskEntity taskEntity = taskService.viewTask(ahp.getTaskId());
        //先删除后保存最终结果
        //model表主键
        deleteAndSaveFinalResult(ahp);
        String dmslId = ahp.getDmslId();
        //汇总权重数据
        Map<String, List<BigDecimal>> parameter = getRatio(ahp, dmslId);
        //任务转栅格获取生成在磁盘上的栅格文件
        String taskResultLayerName= "";
        try {
            taskResultLayerName = getGridFile(taskEntity.getTaskNum(),"3","dzzh_task","SmUserID","dt_id",ahp.getTaskId(),"任务","");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        System.out.println("任务转栅格获取生成在磁盘上的栅格文件获取成功！");

        //地层岩性转栅格获取生成在磁盘上的栅格文件
        //地层岩性矢量转栅格并获取文件信息
        String lithologyVersion = ahp.getLithologyVersion();
        String lithologyResultLayerName= "";
        try {
            lithologyResultLayerName = getGridFile(taskEntity.getTaskNum(),"2","jc_stratum_lithology","values1","data_version",lithologyVersion,"地层岩性",taskResultLayerName);
            System.out.println(lithologyVersion + "版本的地层岩性:{}" + lithologyResultLayerName + "解析成功！");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        //将动峰加速度转栅格并获取文件信息
        String pga02yResultLayerName= "";
        if(StringUtils.isNotBlank(ahp.getA1Version())){
            try {
                pga02yResultLayerName = getGridFile(taskEntity.getTaskNum(),"2","jc_pga_002","year50_pro_exceedance002","data_version",ahp.getA1Version(),"50年超越概率2%的地震峰值加速度数据",taskResultLayerName);
                System.out.println(ahp.getA1Version() + "版本的地震峰值加速度（2%）:{}" + pga02yResultLayerName + "解析成功！");
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }

        String pga10yResultLayerName= "";
        if(StringUtils.isNotBlank(ahp.getA2Version())){
            try {
                pga10yResultLayerName = getGridFile(taskEntity.getTaskNum(),"2","jc_pga_010","year50_pro_exceedance_010","data_version",ahp.getA2Version(),"50年超越概率10%的地震峰值加速度数据",taskResultLayerName);
                System.out.println(ahp.getA2Version() + "版本的地震峰值加速度（10%）:{}" + pga10yResultLayerName + "解析成功！");
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }

        String pga63yResultLayerName= "";
        if(StringUtils.isNotBlank(ahp.getA3Version())){
            try {
                pga63yResultLayerName = getGridFile(taskEntity.getTaskNum(),"2","jc_pga_063","year50_pro_exceedance_063","data_version",ahp.getA3Version(),"50年超越概率63%的地震峰值加速度数据",taskResultLayerName);
                System.out.println(ahp.getA3Version() + "版本的地震峰值加速度（63%）:{}" + pga63yResultLayerName + "解析成功！");
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }

        if(StringUtils.isBlank(ahp.getA1Version()) && StringUtils.isBlank(ahp.getA2Version()) && StringUtils.isBlank(ahp.getA3Version())){
            throw new RuntimeException("评估未完成,请至少选择一类地震动峰值加速度数据版本");
        }
        Map<String, String> paramMap = new HashMap<>();
        //paramMap.put("entity", ahp);
        //获取场地类别-活动构造区
        if(PlatformObjectUtils.isEmpty(ahp.getSiteFileName().get(0))){
            throw new RuntimeException("获取场地类别-活动构造区失败");
        }
        paramMap.put("activeSiteName", ahp.getSiteFileName().get(0));
        //获取场地类别-稳定构造区
        if(PlatformObjectUtils.isEmpty(ahp.getSiteFileName().get(1))){
            throw new RuntimeException("获取场地类别-稳定构造区失败");
        }
        paramMap.put("steadySiteName", ahp.getSiteFileName().get(1));
        //综合地形指数栅格文件
        String ctResultLayerName = ahp.getLandFormFileName();
        paramMap.put("ctResultLayerName", ctResultLayerName);
        try {
            if(PlatformObjectUtils.isEmpty(taskResultLayerName)){
                throw new RuntimeException("任务转栅格失败");
            }
            paramMap.put("taskResultLayerName", taskResultLayerName);
        } catch (Exception e) {
            throw new RuntimeException("任务转栅格失败");
        }
        try {
            if(PlatformObjectUtils.isEmpty(lithologyResultLayerName)){
                throw new RuntimeException("地层岩性矢量转栅格失败");
            }
            paramMap.put("lithologyResultLayerName", lithologyResultLayerName);
        } catch (Exception e) {
            throw new RuntimeException("地层岩性矢量转栅格失败");
        }
        if(PlatformObjectUtils.isEmpty(pga02yResultLayerName) && StringUtils.isNotBlank(ahp.getA1Version())){
            throw new RuntimeException("评估未完成，动峰加速度002转栅格失败");
        }
        paramMap.put("pga02yResultLayerName", pga02yResultLayerName);

        if(PlatformObjectUtils.isEmpty(pga10yResultLayerName) && StringUtils.isNotBlank(ahp.getA2Version())){
            throw new RuntimeException("评估未完成，动峰加速度010转栅格失败");
        }
        paramMap.put("pga10yResultLayerName", pga10yResultLayerName);

        if(PlatformObjectUtils.isEmpty(pga63yResultLayerName) && StringUtils.isNotBlank(ahp.getA3Version())){
            throw new RuntimeException("评估未完成，动峰加速度063转栅格失败");
        }
        paramMap.put("pga63yResultLayerName", pga63yResultLayerName);

        try {
            if(PlatformObjectUtils.isEmpty(ahp.getRiverFileName())){
                throw new RuntimeException("水系获取失败");
            }
            paramMap.put("waterName", ahp.getRiverFileName());
        } catch (Exception e) {
            throw new RuntimeException("水系获取失败");
        }
        RestResponse restResponse = null;
        try {
            restResponse = getData(paramMap, parameter);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        if (restResponse.getCode() != 200) {
            throw new RuntimeException("评估计算失败");
        }
        JSONArray jsonArray = JSON.parseObject(restResponse.getData().toString()).getJSONArray("resultLayerName");
        List<AhpResultEntity> ahpResultEntityList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            String fileName = jsonArray.getString(i);
            //根据重分类的自然分割法，获取液化危害指数划分
            String reclassifyFileName = getGridFile("reclassify", fileName, "");
            AhpResultEntity ahpResultEntity = AhpResultEntity.builder().build();
            ahpResultEntity.setDiaId(UUIDGenerator.getUUID());
            //String resultLayerName = resultLayerName1 + "_计算_" + currTime + "_" + 动峰加速度+"_"+场地类别;
            //动峰加速度
            String pga = fileName.split("_")[fileName.split("_").length - 2];
            //场地类别
            String site = fileName.split("_")[fileName.split("_").length - 1];
            if ("002".equals(pga)) {
                ahpResultEntity.setPga("50年超越概率2%");
            } else if ("010".equals(pga)) {
                ahpResultEntity.setPga("50年超越概率10%");
            } else {
                ahpResultEntity.setPga("50年超越概率63%");
            }
            if ("1".equals(site)) {
                ahpResultEntity.setPlaceType("活动构造区");
            } else if ("2".equals(site)) {
                ahpResultEntity.setPlaceType("稳定大陆区");
            }
            ahpResultEntity.setFilePath(reclassifyFileName);
            ahpResultEntity.setTaskId(ahp.getTaskId());
            ahpResultEntity.setDmslId(dmslId);
            ahpResultEntity.setCreateTime(new Date());
            ahpResultEntity.setUserId(PlatformSessionContext.getUserID());
            ahpResultEntityList.add(ahpResultEntity);
        }
        if (ahpResultEntityList.size() > 0) {
            sandLiquefactionRepository.batchSave(ahpResultEntityList);
        }
        //保存自定义的参数
        if (1!=ahp.getSelectedMatrix()) {
            AhpRatioVO vo = new AhpRatioVO();
            BeanUtils.copyProperties(ahp,vo);
            String darId = UUIDGenerator.getUUID();
            Field[] fields = vo.getClass().getDeclaredFields();
            if(PlatformObjectUtils.isNotEmpty(fields)){
                JSONObject json = new JSONObject();
                for(Field field:fields){
                    field.setAccessible(true);
                    AddData annotation = field.getAnnotation(AddData.class);
                    if(annotation==null){
                        continue;
                    }
                    String name = field.getName();
                    Object value = field.get(vo);
                    json.put(name,value);
                }
                if(json.size()>0){
                    String ratio = json.toJSONString();
                    //保存系数信息
                    sandLiquefactionRepository.saveRatio(darId,ahp.getTaskId(),dmslId,ratio);
                }
            }
        }
        //延时5秒，防止前端不显示结果超图图层
        Thread.sleep(5000);
    }

    //获取任务区域中的所有的水系
    private String getAndBufferWater(TaskEntity taskEntity,List<BigDecimal> waterList) throws Exception{
        /*//先删除之前缓存的水系信息
        Integer num = sandLiquefactionRepository.getRiverNum(taskEntity.getDtId());
        if(num==0){
            //远程基础数据获取任务区域范围内的水系数据
            JSONObject valueMap = new JSONObject();
            valueMap.put("geom", taskEntity.getGeom());
            String url2 = basicDataUrl + "/datacenter/jcHydl/findAllUnion"; //Object obj = drillService.getJCSJ(url2, 4, valueMap);
            RestResponse obj = drillService.getJCSJ(url2, 4, valueMap);
            if(PlatformObjectUtils.isEmpty(obj)){
                throw new RuntimeException("该区域没有水系数据");
            }
            JSONArray jsonArray = (JSONArray) obj.getData();
            JSONObject  jsonObject = jsonArray.getJSONObject(0);
            if (PlatformObjectUtils.isEmpty(jsonObject.getString("geom"))) {
                //continue;
                throw new RuntimeException("未获取到水系数据的空间数据，无法进行计算！");
            }
            //远程基础数据获得水系信息并将水系信息保存在地质灾害数据库中方便后续操作
            getAndSaveWater(jsonObject,taskEntity,waterList);
        }
        //sandLiquefactionRepository.deleteByTaskId(taskEntity.getDtId());
        //生成水系文件
        Map<String, Object> map4 = new HashMap<>();
        map4.put("type", "vectorTif-3");
        map4.put("layerName", "dzzh_count_buffer");//矢量转栅格的数据集
        map4.put("clipLayerName", "dzzh_task");//边界数据集
        map4.put("fieldName", "values1");//用于生成栅格值的矢量数据的字段，默认用超图自身的字段SmUserID值为0
        //过滤其他数据的表达式，即只保留符合sql条件的数据
//        map4.put("sqlFilter", "task_id='" + taskEntity.getDtId() + "' and type1='2' and flag='2'");//"dt_id
        map4.put("sqlFilter", "task_id='" + taskEntity.getDtId() + "' and type1='2'");//"dt_id
        // !='f93240cd9e90411b9da7f3d604d104ec'";
        //边界过滤其他数据的表达式，即只保留符合sql条件的数据
        map4.put("sqlFilterClip", "task_num='" + taskEntity.getTaskNum() + "' and del_flag='0'");//"task_num
        // !='f93240cd9e90411b9da7f3d604d104ec'";
        RestResponse serverToken4 = hypergraphService.getServerToken(map4);
        if (serverToken4.getCode() != 200) {
            throw new RuntimeException("该区域没有水系数据");
        }
        return JSON.parseObject(JSON.toJSONString(serverToken4.getData()))
                .getString("resultLayerName");*/
        //查询数据库矢量数据到dzzhTifCount--任务区域
        String currTime = System.currentTimeMillis() + "";
        String clipLayerName = "temp_dzzh任务_" + currTime;
        String sqlFilter = "dt_id='"+taskEntity.getDtId()+"'";
        Map<String, Object> map0 = new HashMap<>();
        map0.put("type", "dzzhVectorQuery");
        map0.put("layerName", "dzzh_task");
        map0.put("resultLayerName", clipLayerName);
        map0.put("sqlFilter", sqlFilter);
        map0.put("queryType", "fxfzdzzh");
        RestResponse serverToken0 = hypergraphService.getServerToken(map0);
        if (serverToken0.getCode() != 200) {
            return "";
        }
        //砂土液化层次分析河流分级栅格计算
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("type", "waterVectorBufferTif");
        requestMap.put("layerName", clipLayerName);
        requestMap.put("waterList", waterList);
        requestMap.put("timeStamp", currTime);
        RestResponse serverToken = hypergraphService.getServerToken(requestMap);
        if (serverToken.getCode() != 200) {
            return "";
        }
        return JSON.parseObject(JSON.toJSONString(serverToken.getData()))
                .getString("resultLayerName");
    }

    /**
     * 组织水系数据进行本地数据库表数据保存
     */
    private void getAndSaveWater(JSONObject  jsonObject,TaskEntity taskEntity,List<BigDecimal> waterList) throws Exception{
        //String bufferGeomText = lawAnalysisRepository.getBufferByGeomMeter(taskEntity.getTaskRegion(), 2 * 1000);
        //1,0-49;2,50-99;3,100-149;4,150-199;5,>200
        Integer number1 = 50, number2 = 0;
        for (int key = 0; key < 5; key++) {
            switch (String.valueOf(key)) {
                case "0":
                    number1 = 49;
                    number2 = 0;
                    break;
                case "1":
                    number1 = 99;
                    number2 = 50;
                    break;
                case "2":
                    number1 = 149;
                    number2 = 100;
                    break;
                case "3":
                    number1 = 199;
                    number2 = 150;
                    break;
                case "4":
                    number1 = 249;
                    number2 = 200;
                    break;
            }
            BigDecimal param3 = getParam3(String.valueOf(key),waterList);
            String geoms = this.getByGeom2(taskEntity.getGeom(), jsonObject.getString("geom"),null, number1, number2);
            if(StringUtils.isBlank(geoms)){
                throw new RuntimeException("未获取到水系数据的空间数据，无法进行计算！");
            }
            if (geoms.indexOf("MULTIPOLYGON") != 0) {
                if (geoms.indexOf("POLYGON") == 0) {
                    geoms = geoms.replace("POLYGON", "MULTIPOLYGON(") + ")";
                } else {
                    continue;
                }
            }
            DzzhCountBuffer dzzhCountBuffer = new DzzhCountBuffer();
            dzzhCountBuffer.setId(UUIDGenerator.getUUID());
            dzzhCountBuffer.setType("2");
            dzzhCountBuffer.setValues1(param3);
            dzzhCountBuffer.setGeomText(geoms);
            dzzhCountBuffer.setTaskId(taskEntity.getDtId());
            //dzzhCountBuffer.setFlag("2");
            try {
                eqLandslideRepository.saveDzzhCountBuffer(dzzhCountBuffer);
            } catch (UncategorizedSQLException e) {
                throw new RuntimeException("保存水系数据失败，无法进行计算！");
            }
        }
        //刷新指定超图工作空间数据源数据集
        hypergraphService.getWorkspaceReload("dzzh_count_buffer");
    }

    private String getByGeom2(String geom, String geom1,String bufferGeomText, Integer number1, Integer number2) {
//        String geomResult = "";
//        String sql = "";
//        try{
//            //根据空间数据wkt获取投影坐标EPSG
//            int epsg = elevationMapService.getEPSGFromGeomText(geom);
//            if (number2 == 200) {
//                sql = "select st_astext(st_intersection(st_difference(";
//                sql = sql + "(select st_geometryfromtext('"+geom+"',4490) as polygon), ";
//                sql = sql + "st_transform(st_buffer(st_transform(a.geom, "+epsg+"),"+number2+"),4490)),st_geomfromtext('"+geom+"',4490))) as geom " +
//                        "from (select st_intersection((select st_geometryfromtext('"+geom1+"',4490) as line), " +
//                        "(select st_geometryfromtext('"+bufferGeomText+"',4490) as polygon)) as geom) a";
//            } else {
//                sql = "select st_astext(st_intersection(st_difference(";
//                sql = sql + "st_transform(st_buffer(st_transform(a.geom, " + epsg + "),"+number1+"),4490), ";
//                sql = sql + "st_transform(st_buffer(st_transform(a.geom, "+epsg+"),"+number2+"),4490) ),st_geomfromtext('"+geom+"',4490))) as geom " +
//                        "from (select st_intersection((select st_geometryfromtext('"+geom1+"',4490) as line), " +
//                        "(select st_geometryfromtext('"+bufferGeomText+"',4490) as polygon)) as geom) a";
//            }
////            if (number2 == 200) {
////                sql = "select st_geomfromtext((select st_astext(st_difference(st_intersection( ";
////                sql = sql + "(select st_geometryfromtext('"+geom+"',4490) as polygon)),";
////                sql = sql + "(select st_geometryfromtext('"+geom+"',4490) as polygon)), st_intersection(st_transform(st_buffer(st_transform(a.geom, " + epsg + "),"+number2+"),4490), " +
////                        "(select st_geometryfromtext('"+geom1+"',4490) as polygon)))) as geom from (select st_intersection((select st_geometryfromtext('"+geom+"',4490) as line), " +
////                        "(select st_geometryfromtext('"+geom+"',4490) as polygon)) as geom) a) as geom";
////            } else {
////                sql = "select (select st_astext(st_difference(st_intersection( ";
////                sql = sql + "st_transform(st_buffer(st_transform(a.geom, " + epsg + "),"+number1+"),4490),";
////                sql = sql + "(select st_geometryfromtext('"+geom+"',4490) as polygon)), st_intersection(st_transform(st_buffer(st_transform(a.geom, " + epsg + "),"+number2+"),4490), " +
////                        "(select st_geometryfromtext('"+geom1+"',4490) as polygon)))) as geom from (select st_intersection((select st_geometryfromtext('"+geom+"',4490) as line), " +
////                        "(select st_geometryfromtext('"+geom+"',4490) as polygon)) as geom) a) as geom";
////            }
//            geomResult = jdbcTemplate.queryForObject(sql,String.class);
//        }catch (Exception ex){
//            ex.printStackTrace();
//        }
//
//        return geomResult;
        //根据空间数据wkt获取投影坐标EPSG
        int epsg = elevationMapService.getEPSGFromGeomText(geom);
        String sql = "select st_astext(st_difference(";
        if (number2 == 200) {
            sql = sql + "(select st_geometryfromtext('"+geom+"',4490) as polygon), ";
        } else {
            sql = sql + "st_transform(st_buffer(st_transform(a.geom, " + epsg + "),"+number1+"),4490), ";
        }
        sql = sql + "st_transform(st_buffer(st_transform(a.geom, "+epsg+"),"+number2+"),4490))) as geom " +
                "from (select st_geometryfromtext('"+geom1+"',4490) as geom) a";
        return jdbcTemplate.queryForObject(sql, String.class);
    }

    private BigDecimal getParam3(String key,List<BigDecimal> waterList) {
        BigDecimal param3 = BigDecimal.ZERO;
        switch (key) {
            case "0":
                param3 = waterList.get(0);
                break;
            case "1":
                param3 = waterList.get(1);
                break;
            case "2":
                param3 = waterList.get(2);
                break;
            case "3":
                param3 = waterList.get(3);
                break;
            case "4":
                param3 = waterList.get(4);
                break;
        }
        return param3;
    }

    //根据高程版本获取高程文件
    private String getGcFileByVersion(String altitudeVersion) {
        String url = basicDataUrl+"/datacenter/sysDataVersion/dzdzzhpg/getDataFileInfo?versionCode="+altitudeVersion;
        JSONArray JSONArray =(JSONArray) drillService.getJCSJ(url,3,new JSONObject()).getData();
        String fileName = "";
        if(PlatformObjectUtils.isNotEmpty(JSONArray)){
            JSONObject jsonObject = (JSONObject) JSONArray.get(0);
            String filePath = (String) jsonObject.get("attachName");//jcJsonObject.getString("filePath");
            //获取文件名
            int index = filePath.lastIndexOf("/");
            String layerName = filePath.substring(index + 1, filePath.length());
            fileName = StrUtil.removeSuffix(layerName,".tif");
        }
        return fileName;
    }

    private Map<String, List<BigDecimal>> getRatio(Ahp ahp,String dmslId) throws Exception {
        Map<String, List<BigDecimal>> mapMap = new HashMap<>();
        if (1==ahp.getSelectedMatrix()) {
            mapMap = buildRatio();
        } else {
          // 构建矩阵并进行一致性检验后构造固定格式Map
            Map<String, Map<String, Object>> map = getAndSaveByModelType(ahp, dmslId);
          // 获取各个致灾因子的权重数据
            Map<String, Object> appraiseMap = map.get("砂土液化危险性评价");
            mapMap.put("砂土液化危险性评价",(List<BigDecimal>) appraiseMap.get("result"));
            Map<String, Object> pgaMap = map.get("地震动参数");
            mapMap.put("地震动参数",(List<BigDecimal>) pgaMap.get("result"));
            Map<String, Object> waterMap = map.get("距河流距离");
            mapMap.put("距河流距离",(List<BigDecimal>) waterMap.get("result"));
            Map<String, Object> placeFormMap = map.get("场地类别");
            mapMap.put("场地类别",(List<BigDecimal>) placeFormMap.get("result"));
            Map<String, Object> landFormMap = map.get("综合地形指数");
            mapMap.put("综合地形指数",(List<BigDecimal>) landFormMap.get("result"));
            Map<String, Object> lithologyMap = map.get("土层年代");
            mapMap.put("土层年代",(List<BigDecimal>) lithologyMap.get("result"));
        }
        return mapMap;
    }
    private RestResponse getData(Map<String, String> map,Map<String, List<BigDecimal>> ratio) throws Exception{
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray2 = new JSONArray();
        String taskResultLayerName=  map.get("taskResultLayerName");
        String lithologyResultLayerName=  map.get("lithologyResultLayerName");
        String ctResultLayerName= map.get("ctResultLayerName");
        List<String> pga0List = new ArrayList<>(3);
        String pga02yResultLayerName=  map.get("pga02yResultLayerName");
        if(StringUtils.isNotBlank(pga02yResultLayerName)){
            pga0List.add(pga02yResultLayerName);
        }
        String pga10yResultLayerName=  map.get("pga10yResultLayerName");
        if(StringUtils.isNotBlank(pga10yResultLayerName)){
            pga0List.add(pga10yResultLayerName);
        }
        String pga63yResultLayerName=  map.get("pga63yResultLayerName");
        if(StringUtils.isNotBlank(pga63yResultLayerName)){
            pga0List.add(pga63yResultLayerName);
        }
        String activeSiteName=  map.get("activeSiteName");
        String steadySiteName=  map.get("steadySiteName");
        String waterName =  map.get("waterName");
        List<BigDecimal> soilLayerAge = ratio.get("土层年代");
        List<BigDecimal> appraise = ratio.get("砂土液化危险性评价");
        List<BigDecimal> pgaList = ratio.get("地震动参数");
        List<BigDecimal> landFormList = ratio.get("综合地形指数");
        List<BigDecimal> siteList = ratio.get("场地类别");
        StringBuilder countString=
                new StringBuilder("Con([dzzhTifCount." + lithologyResultLayerName + "] <=1," + soilLayerAge.get(0) + ", Con([dzzhTifCount." + lithologyResultLayerName + "]<=5," + soilLayerAge.get(1) + ", Con([dzzhTifCount." + lithologyResultLayerName + "]<=12," + soilLayerAge.get(2) + ",Con([dzzhTifCount." + lithologyResultLayerName + "]<=14," + soilLayerAge.get(3) + ",0))))*" + appraise.get(0) + "+" +
                        "Con([dzzhTifCount." + ctResultLayerName + "] <4," + landFormList.get(0) + ",Con([dzzhTifCount." + ctResultLayerName + "]<6," + landFormList.get(1) + ", Con([dzzhTifCount." + ctResultLayerName + "]<8," + landFormList.get(2) + ",Con([dzzhTifCount." + ctResultLayerName + "]<10," + landFormList.get(3) + ",Con([dzzhTifCount." + ctResultLayerName + "]>=10," + landFormList.get(4) + ",0)))))*" + appraise.get(1) + "+" +
                        "[dzzhTifCount." + waterName + "]*" + appraise.get(3) + "+");

        //地动峰加速度
        //for (int i1 = 1; i1 < 4; i1++) {
        int i1 = 1;
        for(String pga:pga0List){
            String pgaStr = pga.split("_")[3];
            StringBuilder pagBuild = new StringBuilder();
            pagBuild.append(countString);
            String resultLayerName_6 = "";
//            if (i1 == 1) {
//                resultLayerName_6 = pga02yResultLayerName;
//            } else if (i1 == 2) {
//                resultLayerName_6 = pga10yResultLayerName;
//            } else {
//                resultLayerName_6 = pga63yResultLayerName;
//            }
            resultLayerName_6 = pga;
            pagBuild.append("Con([dzzhTifCount.").append(resultLayerName_6).append("]<=0.05,").append(pgaList.get(0)).append(",Con([dzzhTifCount.").append(resultLayerName_6).append("]>0.05,").append(pgaList.get(1)).append(",0))*").append(appraise.get(2));
            //场地类别分为活动构造区和稳定大陆区
            for(int i11=1;i11<3;i11++){
                StringBuilder landform = new StringBuilder();
                landform.append(pagBuild);
                //int i11 =1;
                String siteName = "";
                if (i11 == 1) {
                    siteName = activeSiteName;
                    landform.append("+").append("Con([dzzhTifCount.").append(siteName).append("]==0.751,").append(siteList.get(0)).append(",Con([dzzhTifCount.").append(siteName).append("]==0.178,").append(siteList.get(1)).append(",Con([dzzhTifCount.").append(siteName).append("]==0.070,").append(siteList.get(2)).append(",0.751)))*").append(appraise.get(4));
                } else {
                    siteName = steadySiteName;
                    landform.append("+").append("Con([dzzhTifCount.").append(siteName).append("]==0.751,").append(siteList.get(0)).append(",Con([dzzhTifCount.").append(siteName).append("]==0.178,").append(siteList.get(1)).append(",Con([dzzhTifCount.").append(siteName).append("]==0.070,").append(siteList.get(2)).append(",0.751)))*").append(appraise.get(4));
                }
                //栅格计算
//                Map<String, Object> map2 = new HashMap<>();
//                map2.put("type", "countMapsTif");
//                String resultLayerName = taskResultLayerName + "_计算_" + System.currentTimeMillis() + "_" +i1+"_"+ i11;//裁剪计算结果数据集
//                map2.put("layerName", resultLayerName);
//                map2.put("countString", countString.toString());
//                map2.put("mapsName", "砂土液化层次分析法-图例.xml");
//                RestResponse serverToken = hypergraphService.getServerToken(map2);
                //栅格计算
                Map<String, Object> map2 = new HashMap<>();
                map2.put("type", "countTif");
                String resultLayerName = taskResultLayerName + "_计算_" + System.currentTimeMillis() + "_" +pgaStr+"_"+ i11;//裁剪计算结果数据集
                map2.put("layerName", resultLayerName);
                map2.put("countString", landform.toString());
                RestResponse serverToken = hypergraphService.getServerToken(map2);
                if(serverToken.getCode()!=200){
                   throw new RuntimeException("计算未完成，评估失败");
                }
                jsonArray2.add(resultLayerName);
            }
            i1++;
        }
        if(jsonArray2.size()==0){
            return RestResponse.fail("计算失败");
        }
        jsonObject.put("resultLayerName", jsonArray2);
        return RestResponse.succeed(jsonObject);
    }

    //根据高程版本获取磁盘高程文件
    private String getElevation(String gcFileName) throws Exception {
        //对高程数据进行裁剪
        Map<String,Object> map = new HashMap<>();
        map.put("type", "demHslCount");
        map.put("layerName", gcFileName);
        RestResponse serverToken = hypergraphService.getServerToken(map);
        if (serverToken.getCode() != 200) {
            throw new RuntimeException("DEM高程计算汇水量失败");
        }
        /*//坡度
        String pdLayerName = JSON.parseObject(JSON.toJSONString(serverToken.getData())).getString("pd");
        //汇水量
        String hslLayerName = JSON.parseObject(JSON.toJSONString(serverToken.getData())).getString("hsl");
        String countString = "ln([dzzhTifCount."+hslLayerName+"]/tan(Con([dzzhTifCount."+pdLayerName+"]<=0,0.00001,[dzzhTifCount."+pdLayerName+"]*3.1415926/180)))";
        Map<String,Object> gcMap = new HashMap<>();
//        gcMap.put("type","countTif");
//        gcMap.put("countString",countString);
//        gcMap.put("layerName", "gc"+System.currentTimeMillis());
//        serverToken = hypergraphService.getServerToken(gcMap);
//        return JSON.toJSONString(serverToken.getData());
        gcMap.put("type","countMapsTif");
        gcMap.put("countString",countString);
        gcMap.put("layerName", "final_综合地形指数"+System.currentTimeMillis());
        gcMap.put("mapsName", "砂土综合地形指数-图例.xml");
        serverToken = hypergraphService.getServerToken(gcMap);*/
        return JSON.toJSONString(serverToken.getData());
    }
    //获取矢量转栅格后的文件
    private String getGridFile(String taskNum,String type,String layerName,String fieldName,String field,String fieldValue,String dataType,String taskFileName) throws Exception{
        Map<String, Object> map = new HashMap<>();
        map.put("type", "vectorTif-"+type);
        map.put("layerName", layerName);//矢量转栅格的数据集
        map.put("clipLayerName", taskFileName);//边界数据集
        map.put("fieldName", fieldName);//用于生成栅格值的矢量数据的字段，默认用超图自身的字段SmUserID值为0
        //过滤其他数据的表达式，即只保留符合sql条件的数据
        map.put("sqlFilter", field+"='" + fieldValue + "' and del_flag='0'");//"dt_id!='f93240cd9e90411b9da7f3d604d104ec'";
        //边界过滤其他数据的表达式，即只保留符合sql条件的数据
        map.put("sqlFilterClip", "task_num='" + taskNum + "' and del_flag='0'");//"dt_id!='f93240cd9e90411b9da7f3d604d104ec'";
        RestResponse serverToken = hypergraphService.getServerToken(map);
        if (serverToken.getCode()!=200) {
            throw  new RuntimeException("该区域没有" + fieldValue + "版本的"+dataType+"数据");
        }
        return JSON.parseObject(JSON.toJSONString(serverToken.getData()))
                .getString("resultLayerName");
    }
    //根据高程文件获取场地类别、综合地形指数
    private String getGridFile(String type,String layerName,String flag){
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        map.put("layerName", layerName);
        map.put("flag", flag);
        RestResponse serverToken = hypergraphService.getServerToken(map);
        if (serverToken.getCode() != 200) {
            if(StringUtils.isNotBlank(flag)){
                if ("1".equals(flag)) {
                    return "场地类别活动构造区计算失败";
                }else if ("2".equals(flag)) {
                    return "场地类别稳定大陆区计算失败";
                }
            }else{
                return "最终评估计算失败";
            }
        }
        return JSON.parseObject(JSON.toJSONString(serverToken.getData()))
                .getString("layerName");
    }

    private Map<String, List<BigDecimal>> buildRatio() {
        Map<String, List<BigDecimal>> map = new HashMap<>(6);
        List<BigDecimal> appraiseList = new ArrayList<>();
        appraiseList.add(BigDecimal.valueOf(0.434));
        appraiseList.add(BigDecimal.valueOf(0.271));
        appraiseList.add(BigDecimal.valueOf(0.172));
        appraiseList.add(BigDecimal.valueOf(0.076));
        appraiseList.add(BigDecimal.valueOf(0.047));
        map.put("砂土液化危险性评价", appraiseList);
        List<BigDecimal> pgaList = new ArrayList<>();
        pgaList.add(BigDecimal.valueOf(0.333));
        pgaList.add(BigDecimal.valueOf(0.667));
        map.put("地震动参数", pgaList);
        List<BigDecimal> waterList = new ArrayList<>();
        waterList.add(BigDecimal.valueOf(0.472));
        waterList.add(BigDecimal.valueOf(0.292));
        waterList.add(BigDecimal.valueOf(0.122));
        waterList.add(BigDecimal.valueOf(0.075));
        waterList.add(BigDecimal.valueOf(0.039));
        map.put("距河流距离", waterList);
        List<BigDecimal> placeList = new ArrayList<>();
        placeList.add(BigDecimal.valueOf(0.751));
        placeList.add(BigDecimal.valueOf(0.178));
        placeList.add(BigDecimal.valueOf(0.070));
        map.put("场地类别", placeList);
        List<BigDecimal> landFormList = new ArrayList<>();
        landFormList.add(BigDecimal.valueOf(0.044));
        landFormList.add(BigDecimal.valueOf(0.075));
        landFormList.add(BigDecimal.valueOf(0.143));
        landFormList.add(BigDecimal.valueOf(0.268));
        landFormList.add(BigDecimal.valueOf(0.471));
        map.put("综合地形指数", landFormList);
        List<BigDecimal> resultList = new ArrayList<>();
        resultList.add(BigDecimal.valueOf(0.560));
        resultList.add(BigDecimal.valueOf(0.272));
        resultList.add(BigDecimal.valueOf(0.131));
        resultList.add(BigDecimal.valueOf(0.037));
        map.put("土层年代", resultList);
        return map;
    }

    /**
     * 和综合滴地形指数分类的范围比对获取地形权重集合中应取数据的下标
     */
    private Integer getLandFormWeight(BigDecimal num) {
        if (num.compareTo(BigDecimal.ZERO) >= 0 && num.compareTo(BigDecimal.valueOf(4)) < 0) {
            return 0;
        } else if (num.compareTo(BigDecimal.valueOf(4)) >= 0 && num.compareTo(BigDecimal.valueOf(6)) < 0) {
            return 1;
        } else if (num.compareTo(BigDecimal.valueOf(6)) >= 0 && num.compareTo(BigDecimal.valueOf(8)) < 0) {
            return 2;
        } else if (num.compareTo(BigDecimal.valueOf(8)) >= 0 && num.compareTo(BigDecimal.valueOf(10)) < 0) {
            return 3;
        }
        return 4;
    }

    /**
     * 根据栅格到河流的距离获取权重集合中的下标信息
     */
    private Integer getWaterWeight(BigDecimal minDistance) {
        if (minDistance.compareTo(BigDecimal.ZERO) >= 0 && minDistance.compareTo(BigDecimal.valueOf(50)) < 0) {
            return 0;
        } else if (minDistance.compareTo(BigDecimal.valueOf(50)) >= 0 && minDistance.compareTo(BigDecimal.valueOf(100)) < 0) {
            return 1;
        } else if (minDistance.compareTo(BigDecimal.valueOf(100)) >= 0 && minDistance.compareTo(BigDecimal.valueOf(150)) < 0) {
            return 2;
        } else if (minDistance.compareTo(BigDecimal.valueOf(150)) >= 0 && minDistance.compareTo(BigDecimal.valueOf(200)) < 0) {
            return 3;
        } else {
            return 4;
        }
    }

    private Integer getParam6(BigDecimal num) {
        int param6 = 0;
        if (num.compareTo(BigDecimal.valueOf(0.05)) > 0) {
            param6 = 1;
        }
        return param6;
    }


    private JSONArray getUrl(String versionCode, String geom, String typeCode, String geomType) {
        JSONObject valueMap = new JSONObject();
        valueMap.put("versionCode", versionCode);
        valueMap.put("geom", geom);
        valueMap.put("typeCode",typeCode);
        valueMap.put("geomType",geomType);
        String url = basicDataUrl + "/datacenter/sysDataVersion/queryAllByVersionCode";
        JSONArray jsonArray = (JSONArray) drillService.getJCSJ(url, 4, valueMap).getData();
        return jsonArray;
//        return basicDataUrl + "/datacenter/sysDataVersion/queryAllByVersionCode?versionCode=" + versionCode + "&typeCode=" + typeCode +"&geomType="+ geomType + "&geom=" + geom;
    }

    /**
     * 和土层年代分类的信息比对获取土层年代权重集合中应取数据的下标
     */
    private Integer getLithologyYears(String years) {
        Integer lithologyYears = 0;
        switch (years) {
            // 晚全新世 Qh3  0
            case "Q[h](3)":
                lithologyYears = 0;
                break;
            //全新世 1
            case "Q[h](2)":
            case "Q[h](2-3)":
            case "Q[h](1-2)":
            case "Q[h](1)":
                lithologyYears = 1;
                break;
            //更新世 2
            case "Q[p](3)-Qh":
            case "Q[p](3-3)":
            case "Q[p](3-2)":
            case "Q[p](3-1)":
            case "Q[p](3)":
            case "Q[p](2)":
                lithologyYears = 2;
                break;
            //早前更新世 3
            case "Q[p](1+2)":
            case "Q[p](1)":
                lithologyYears = 3;
                break;
        }
        return lithologyYears;
    }

    /**
     * 基础数据获取地层岩性数据
     */
    private List<JSONObject> getJcStratumLithologyList(String lithologtCode, String typeCode) {
        String geomType = "";
        String url = basicDataUrl + "/datacenter/sysDataVersion/queryAllByVersionCode?versionCode=" +
                lithologtCode + "&typeCode=" + typeCode + "&geomType=" + geomType;
        JSONObject json = (JSONObject) JSON.toJSON(drillService.getJCSJ(url, 2).getData());
        List<JSONObject> list = (List<JSONObject>) json.get("data");
        return PlatformObjectUtils.isEmpty(list) ? new ArrayList<>() : list;
    }

    private Map<String, Map<String, Object>> getAndSaveByModelType(Ahp ahp, String dmslId) throws Exception {
        //构建矩阵数据
        Map<String, BigDecimal[][]> bigDecimals = getBigDecimals(ahp);
        Map<String, Map<String, Object>> mapMap = new HashMap<>();
        for (String s : bigDecimals.keySet()) {
            //获取值并进行一致性校验
            Map<String, Object> factor = getFactor(bigDecimals.get(s));
            if ("不通过".equals(factor.get("status"))) {
                throw new RuntimeException("您输入的判断矩阵不符合一致性检验要求，请重新调整。");
            }
            mapMap.put(s, factor);
        }
        return mapMap;
    }

    /**
     * 活动构造区对应的场地类型
     */
    private Integer getActiveAreaType(BigDecimal num) {
        if (num.compareTo(BigDecimal.valueOf(1.0).multiply(BigDecimal.valueOf(Math.pow(10, -4)))) < 0) {
            //<1.0E-4
            return -1;
        } else if (num.compareTo(BigDecimal.valueOf(1.0).multiply(BigDecimal.valueOf(Math.pow(10, -4)))) >= 0
                && num.compareTo(BigDecimal.valueOf(0.018)) < 0) {
            //<1.0E-4,2.2E-3
            return 0;
        } else if (num.compareTo(BigDecimal.valueOf(0.018)) >= 0 && num.compareTo(BigDecimal.valueOf(0.138)) < 0) {
            //[0.018,0.138）
            return 1;
        }
        //else if(num.compareTo(BigDecimal.valueOf(0.138))==0){
        //0.138
        return 2;
        //}
    }

    /**
     * 稳定大陆区对应的场地类型
     */
    private Integer getSteadyAreaType(BigDecimal num) {
        if (num.compareTo(BigDecimal.valueOf(2.0).multiply(BigDecimal.valueOf(Math.pow(10, -5)))) < 0) {
            //<2.0E-5
            return -1;
        } else if (num.compareTo(BigDecimal.valueOf(2.0).multiply(BigDecimal.valueOf(Math.pow(10, -5)))) >= 0
                && num.compareTo(BigDecimal.valueOf(7.2).multiply(BigDecimal.valueOf(Math.pow(10, -3)))) < 0) {
            //2.0E-5，7.2E-3
            return 0;
        } else if (num.compareTo(BigDecimal.valueOf(7.2).multiply(BigDecimal.valueOf(Math.pow(10, -3)))) >= 0 && num.compareTo(BigDecimal.valueOf(0.025)) < 0) {
            //7.2E-3，0.025
            return 1;
        }
        //else if(num.compareTo(BigDecimal.valueOf(0.138))==0){
        //0.025
        return 2;
        //}
    }

    private Map<String, Object> getFactor(BigDecimal[][] bigDecimals) {
        Map<String, Object> resultMap = new HashMap<>(2);
        List<BigDecimal> resultList = new ArrayList<>(5);
        if (bigDecimals.length == 1) {
            resultList.add(BigDecimal.ONE);
        } else if (bigDecimals.length == 2) {
            BigDecimal b1 = bigDecimals[0][0].divide(bigDecimals[0][0].add(bigDecimals[1][0]), 12, BigDecimal.ROUND_HALF_UP)
                    .add(bigDecimals[0][1].divide(bigDecimals[0][1].add(bigDecimals[1][1]), 12, BigDecimal.ROUND_HALF_UP));
            BigDecimal b2 = bigDecimals[1][0].divide(bigDecimals[0][0].add(bigDecimals[1][0]), 12, BigDecimal.ROUND_HALF_UP)
                    .add(bigDecimals[1][1].divide(bigDecimals[0][1].add(bigDecimals[1][1]), 12, BigDecimal.ROUND_HALF_UP));

            BigDecimal c1 = b1.divide(b1.add(b2), 12, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(2), 12,
                    BigDecimal.ROUND_HALF_UP);
            resultList.add(c1);
            BigDecimal c2 = b2.divide(b1.add(b2), 12, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(2), 12,
                    BigDecimal.ROUND_HALF_UP);
            resultList.add(c2);
        }else if (bigDecimals.length == 3) {
            BigDecimal b1 = bigDecimals[0][0].divide(bigDecimals[0][0].add(bigDecimals[1][0]).add(bigDecimals[2][0]), 12, BigDecimal.ROUND_HALF_UP)
                    .add(bigDecimals[0][1].divide(bigDecimals[0][1].add(bigDecimals[1][1]).add(bigDecimals[2][1]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[0][2].divide(bigDecimals[0][2].add(bigDecimals[1][2]).add(bigDecimals[2][2]), 12, BigDecimal.ROUND_HALF_UP));
            BigDecimal b2 = bigDecimals[1][0].divide(bigDecimals[0][0].add(bigDecimals[1][0]).add(bigDecimals[2][0]), 12, BigDecimal.ROUND_HALF_UP)
                    .add(bigDecimals[1][1].divide(bigDecimals[0][1].add(bigDecimals[1][1]).add(bigDecimals[2][1]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[1][2].divide(bigDecimals[0][2].add(bigDecimals[1][2]).add(bigDecimals[2][2]), 12, BigDecimal.ROUND_HALF_UP));
            BigDecimal b3 = bigDecimals[2][0].divide(bigDecimals[0][0].add(bigDecimals[1][0]).add(bigDecimals[2][0]), 12, BigDecimal.ROUND_HALF_UP)
                    .add(bigDecimals[2][1].divide(bigDecimals[0][1].add(bigDecimals[1][1]).add(bigDecimals[2][1]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[2][2].divide(bigDecimals[0][2].add(bigDecimals[1][2]).add(bigDecimals[2][2]), 12, BigDecimal.ROUND_HALF_UP));

            BigDecimal sum = b1.add(b2).add(b3);
            BigDecimal c1 = b1.divide(sum, 12, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(3), 12,
                    BigDecimal.ROUND_HALF_UP);
            resultList.add(c1);
            BigDecimal c2 = b2.divide(sum, 12, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(3), 12,
                    BigDecimal.ROUND_HALF_UP);
            resultList.add(c2);
            BigDecimal c3 = b3.divide(sum, 12, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(3), 12,
                    BigDecimal.ROUND_HALF_UP);
            resultList.add(c3);
            //验证，归一化权重
            BigDecimal Aw1= bigDecimals[0][0].multiply(c1).add(bigDecimals[0][1].multiply(c2)).add(bigDecimals[0][2].multiply(c3));
            BigDecimal Aw2= bigDecimals[1][0].multiply(c1).add(bigDecimals[1][1].multiply(c2)).add(bigDecimals[1][2].multiply(c3));
            BigDecimal Aw3= bigDecimals[2][0].multiply(c1).add(bigDecimals[2][1].multiply(c2)).add(bigDecimals[2][2].multiply(c3));
            BigDecimal lamda = (Aw1.divide(c1,12,BigDecimal.ROUND_HALF_UP).add(Aw2.divide(c2,12, BigDecimal.ROUND_HALF_UP))
                    .add(Aw3.divide(c3,12,BigDecimal.ROUND_HALF_UP))).divide(BigDecimal.valueOf(3), 12, BigDecimal.ROUND_HALF_UP);
            BigDecimal CI = (lamda.subtract(BigDecimal.valueOf(3))).divide((BigDecimal.valueOf(3).subtract(BigDecimal.ONE)),12, RoundingMode.HALF_DOWN);
            BigDecimal ri = getRi(3);
            BigDecimal divide = CI.divide(ri, 12, RoundingMode.HALF_DOWN);
            if (divide.compareTo(BigDecimal.valueOf(0.1)) < 0) {
                //校验通过
                resultMap.put("status", "通过");
            } else {
                //校验不通过
                resultMap.put("status", "不通过");
            }
        } else if (bigDecimals.length == 4) {
            BigDecimal b1 = bigDecimals[0][0].divide(bigDecimals[0][0].add(bigDecimals[1][0]).add(bigDecimals[2][0]).add(bigDecimals[3][0]), 12, BigDecimal.ROUND_HALF_UP)
                    .add(bigDecimals[0][1].divide(bigDecimals[0][1].add(bigDecimals[1][1]).add(bigDecimals[2][1]).add(bigDecimals[3][1]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[0][2].divide(bigDecimals[0][2].add(bigDecimals[1][2]).add(bigDecimals[2][2]).add(bigDecimals[3][2]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[0][3].divide(bigDecimals[0][3].add(bigDecimals[1][3]).add(bigDecimals[2][3]).add(bigDecimals[3][3]), 12, BigDecimal.ROUND_HALF_UP));
            BigDecimal b2 = bigDecimals[1][0].divide(bigDecimals[0][0].add(bigDecimals[1][0]).add(bigDecimals[2][0]).add(bigDecimals[3][0]), 12, BigDecimal.ROUND_HALF_UP)
                    .add(bigDecimals[1][1].divide(bigDecimals[0][1].add(bigDecimals[1][1]).add(bigDecimals[2][1]).add(bigDecimals[3][1]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[1][2].divide(bigDecimals[0][2].add(bigDecimals[1][2]).add(bigDecimals[2][2]).add(bigDecimals[3][2]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[1][3].divide(bigDecimals[0][3].add(bigDecimals[1][3]).add(bigDecimals[2][3]).add(bigDecimals[3][3]), 12, BigDecimal.ROUND_HALF_UP));
            BigDecimal b3 = bigDecimals[2][0].divide(bigDecimals[0][0].add(bigDecimals[1][0]).add(bigDecimals[2][0]).add(bigDecimals[3][1]), 12, BigDecimal.ROUND_HALF_UP)
                    .add(bigDecimals[2][1].divide(bigDecimals[0][1].add(bigDecimals[1][1]).add(bigDecimals[2][1]).add(bigDecimals[3][2]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[2][2].divide(bigDecimals[0][2].add(bigDecimals[1][2]).add(bigDecimals[2][2]).add(bigDecimals[3][3]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[2][3].divide(bigDecimals[0][3].add(bigDecimals[1][3]).add(bigDecimals[2][3]).add(bigDecimals[3][3]), 12, BigDecimal.ROUND_HALF_UP));
            BigDecimal b4 = bigDecimals[3][0].divide(bigDecimals[0][0].add(bigDecimals[1][0]).add(bigDecimals[2][0]).add(bigDecimals[3][1]), 12, BigDecimal.ROUND_HALF_UP)
                    .add(bigDecimals[3][1].divide(bigDecimals[0][1].add(bigDecimals[1][1]).add(bigDecimals[2][1]).add(bigDecimals[3][2]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[3][2].divide(bigDecimals[0][2].add(bigDecimals[1][2]).add(bigDecimals[2][2]).add(bigDecimals[3][3]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[3][3].divide(bigDecimals[0][3].add(bigDecimals[1][3]).add(bigDecimals[2][3]).add(bigDecimals[3][3]), 12, BigDecimal.ROUND_HALF_UP));

            BigDecimal sum = b1.add(b2).add(b3).add(b4);
            BigDecimal c1 = b1.divide(sum, 12, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(4), 12,
                    BigDecimal.ROUND_HALF_UP);
            resultList.add(c1);
            BigDecimal c2 = b2.divide(sum, 12, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(4), 12,
                    BigDecimal.ROUND_HALF_UP);
            resultList.add(c2);
            BigDecimal c3 = b3.divide(sum, 12, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(4), 12,
                    BigDecimal.ROUND_HALF_UP);
            resultList.add(c3);
            BigDecimal c4 = b4.divide(sum, 12, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(4), 12,
                    BigDecimal.ROUND_HALF_UP);
            resultList.add(c4);
            //验证，归一化权重
            BigDecimal Aw1=
                    bigDecimals[0][0].multiply(c1).add(bigDecimals[0][1].multiply(c2)).add(bigDecimals[0][2].multiply(c3)).add(bigDecimals[0][3].multiply(c4));
            BigDecimal Aw2= bigDecimals[1][0].multiply(c1).add(bigDecimals[1][1].multiply(c2)).add(bigDecimals[1][2].multiply(c3)).add(bigDecimals[1][3].multiply(c4));
            BigDecimal Aw3= bigDecimals[2][0].multiply(c1).add(bigDecimals[2][1].multiply(c2)).add(bigDecimals[2][2].multiply(c3)).add(bigDecimals[2][3].multiply(c4));
            BigDecimal Aw4= bigDecimals[3][0].multiply(c1).add(bigDecimals[3][1].multiply(c2)).add(bigDecimals[3][2].multiply(c3)).add(bigDecimals[3][3].multiply(c4));
            BigDecimal lamda = (Aw1.divide(c1,12,BigDecimal.ROUND_HALF_UP).add(Aw2.divide(c2,12, BigDecimal.ROUND_HALF_UP))
                    .add(Aw3.divide(c3,12,BigDecimal.ROUND_HALF_UP)).add(Aw4.divide(c4,12,BigDecimal.ROUND_HALF_UP)))
                    .divide(BigDecimal.valueOf(4), 12, BigDecimal.ROUND_HALF_UP);
            BigDecimal CI = (lamda.subtract(BigDecimal.valueOf(4))).divide((BigDecimal.valueOf(4).subtract(BigDecimal.ONE)),12, RoundingMode.HALF_DOWN);
            BigDecimal ri = getRi(4);
            BigDecimal divide = CI.divide(ri, 12, RoundingMode.HALF_DOWN);
            if (divide.compareTo(BigDecimal.valueOf(0.1)) < 0) {
                //校验通过
                resultMap.put("status", "通过");
            } else {
                //校验不通过
                resultMap.put("status", "不通过");
            }
        }else if (bigDecimals.length == 5) {
            BigDecimal b1 = bigDecimals[0][0].divide(bigDecimals[0][0].add(bigDecimals[1][0]).add(bigDecimals[2][0]).add(bigDecimals[3][0]).add(bigDecimals[4][0]), 12, BigDecimal.ROUND_HALF_UP)
                    .add(bigDecimals[0][1].divide(bigDecimals[0][1].add(bigDecimals[1][1]).add(bigDecimals[2][1]).add(bigDecimals[3][1]).add(bigDecimals[4][1]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[0][2].divide(bigDecimals[0][2].add(bigDecimals[1][2]).add(bigDecimals[2][2]).add(bigDecimals[3][2]).add(bigDecimals[4][2]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[0][3].divide(bigDecimals[0][3].add(bigDecimals[1][3]).add(bigDecimals[2][3]).add(bigDecimals[3][3]).add(bigDecimals[4][3]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[0][4].divide(bigDecimals[0][4].add(bigDecimals[1][4]).add(bigDecimals[2][4]).add(bigDecimals[3][4]).add(bigDecimals[4][4]), 12, BigDecimal.ROUND_HALF_UP));
            BigDecimal b2 = bigDecimals[1][0].divide(bigDecimals[0][0].add(bigDecimals[1][0]).add(bigDecimals[2][0]).add(bigDecimals[3][0]).add(bigDecimals[4][0]), 12, BigDecimal.ROUND_HALF_UP)
                    .add(bigDecimals[1][1].divide(bigDecimals[0][1].add(bigDecimals[1][1]).add(bigDecimals[2][1]).add(bigDecimals[3][1]).add(bigDecimals[4][1]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[1][2].divide(bigDecimals[0][2].add(bigDecimals[1][2]).add(bigDecimals[2][2]).add(bigDecimals[3][2]).add(bigDecimals[4][2]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[1][3].divide(bigDecimals[0][3].add(bigDecimals[1][3]).add(bigDecimals[2][3]).add(bigDecimals[3][3]).add(bigDecimals[4][3]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[1][4].divide(bigDecimals[0][4].add(bigDecimals[1][4]).add(bigDecimals[2][4]).add(bigDecimals[3][4]).add(bigDecimals[4][4]), 12, BigDecimal.ROUND_HALF_UP));
            BigDecimal b3 = bigDecimals[2][0].divide(bigDecimals[0][0].add(bigDecimals[1][0]).add(bigDecimals[2][0]).add(bigDecimals[3][0]).add(bigDecimals[4][0]), 12, BigDecimal.ROUND_HALF_UP)
                    .add(bigDecimals[2][1].divide(bigDecimals[0][1].add(bigDecimals[1][1]).add(bigDecimals[2][1]).add(bigDecimals[3][1]).add(bigDecimals[4][1]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[2][2].divide(bigDecimals[0][2].add(bigDecimals[1][2]).add(bigDecimals[2][2]).add(bigDecimals[3][2]).add(bigDecimals[4][2]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[2][3].divide(bigDecimals[0][3].add(bigDecimals[1][3]).add(bigDecimals[2][3]).add(bigDecimals[3][3]).add(bigDecimals[4][3]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[2][4].divide(bigDecimals[0][4].add(bigDecimals[1][4]).add(bigDecimals[2][4]).add(bigDecimals[3][4]).add(bigDecimals[4][4]), 12, BigDecimal.ROUND_HALF_UP));
            BigDecimal b4 = bigDecimals[3][0].divide(bigDecimals[0][0].add(bigDecimals[1][0]).add(bigDecimals[2][0]).add(bigDecimals[3][0]).add(bigDecimals[4][0]), 12, BigDecimal.ROUND_HALF_UP)
                    .add(bigDecimals[3][1].divide(bigDecimals[0][1].add(bigDecimals[1][1]).add(bigDecimals[2][1]).add(bigDecimals[3][1]).add(bigDecimals[4][1]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[3][2].divide(bigDecimals[0][2].add(bigDecimals[1][2]).add(bigDecimals[2][2]).add(bigDecimals[3][3]).add(bigDecimals[4][2]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[3][3].divide(bigDecimals[0][3].add(bigDecimals[1][3]).add(bigDecimals[2][3]).add(bigDecimals[3][3]).add(bigDecimals[4][3]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[3][4].divide(bigDecimals[0][4].add(bigDecimals[1][4]).add(bigDecimals[2][4]).add(bigDecimals[3][4]).add(bigDecimals[4][4]), 12, BigDecimal.ROUND_HALF_UP));
            BigDecimal b5 = bigDecimals[4][0].divide(bigDecimals[0][0].add(bigDecimals[1][0]).add(bigDecimals[2][0]).add(bigDecimals[3][0]).add(bigDecimals[4][0]), 12, BigDecimal.ROUND_HALF_UP)
                    .add(bigDecimals[4][1].divide(bigDecimals[0][1].add(bigDecimals[1][1]).add(bigDecimals[2][1]).add(bigDecimals[3][1]).add(bigDecimals[4][1]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[4][2].divide(bigDecimals[0][2].add(bigDecimals[1][2]).add(bigDecimals[2][2]).add(bigDecimals[3][3]).add(bigDecimals[4][2]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[4][3].divide(bigDecimals[0][3].add(bigDecimals[1][3]).add(bigDecimals[2][3]).add(bigDecimals[3][3]).add(bigDecimals[4][3]), 12, BigDecimal.ROUND_HALF_UP))
                    .add(bigDecimals[4][4].divide(bigDecimals[0][4].add(bigDecimals[1][4]).add(bigDecimals[2][4]).add(bigDecimals[3][4]).add(bigDecimals[4][4]), 12, BigDecimal.ROUND_HALF_UP));
            BigDecimal sum = b1.add(b2).add(b3).add(b4).add(b5);
            BigDecimal c1 = b1.divide(sum, 12, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(5), 12,
                    BigDecimal.ROUND_HALF_UP);
            resultList.add(c1);
            BigDecimal c2 = b2.divide(sum, 12, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(5), 12,
                    BigDecimal.ROUND_HALF_UP);
            resultList.add(c2);
            BigDecimal c3 = b3.divide(sum, 12, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(5), 12,
                    BigDecimal.ROUND_HALF_UP);
            resultList.add(c3);
            BigDecimal c4 = b4.divide(sum, 12, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(5), 12,
                    BigDecimal.ROUND_HALF_UP);
            resultList.add(c4);
            BigDecimal c5 = b5.divide(sum, 12, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(5), 12,
                    BigDecimal.ROUND_HALF_UP);
            resultList.add(c5);
            //验证，归一化权重
            BigDecimal Aw1=
                    bigDecimals[0][0].multiply(c1).add(bigDecimals[0][1].multiply(c2)).add(bigDecimals[0][2].multiply(c3)).add(bigDecimals[0][3].multiply(c4)).add(bigDecimals[0][4].multiply(c5));
            BigDecimal Aw2= bigDecimals[1][0].multiply(c1).add(bigDecimals[1][1].multiply(c2)).add(bigDecimals[1][2].multiply(c3)).add(bigDecimals[1][3].multiply(c4)).add(bigDecimals[1][4].multiply(c5));
            BigDecimal Aw3= bigDecimals[2][0].multiply(c1).add(bigDecimals[2][1].multiply(c2)).add(bigDecimals[2][2].multiply(c3)).add(bigDecimals[2][3].multiply(c4)).add(bigDecimals[2][4].multiply(c5));
            BigDecimal Aw4= bigDecimals[3][0].multiply(c1).add(bigDecimals[3][1].multiply(c2)).add(bigDecimals[3][2].multiply(c3)).add(bigDecimals[3][3].multiply(c4)).add(bigDecimals[3][4].multiply(c5));
            BigDecimal Aw5= bigDecimals[4][0].multiply(c1).add(bigDecimals[4][1].multiply(c2)).add(bigDecimals[4][2].multiply(c3)).add(bigDecimals[4][3].multiply(c4)).add(bigDecimals[4][4].multiply(c5));
            BigDecimal lamda = (Aw1.divide(c1,12,BigDecimal.ROUND_HALF_UP).add(Aw2.divide(c2,12, BigDecimal.ROUND_HALF_UP))
                    .add(Aw3.divide(c3,12,BigDecimal.ROUND_HALF_UP)).add(Aw4.divide(c4,12,BigDecimal.ROUND_HALF_UP)).add(Aw5.divide(c5,12,BigDecimal.ROUND_HALF_UP)))
                    .divide(BigDecimal.valueOf(5), 12, BigDecimal.ROUND_HALF_UP);
            BigDecimal CI = (lamda.subtract(BigDecimal.valueOf(5))).divide((BigDecimal.valueOf(5).subtract(BigDecimal.ONE)),12, RoundingMode.HALF_DOWN);
            BigDecimal ri = getRi(5);
            BigDecimal divide = CI.divide(ri, 12, RoundingMode.HALF_DOWN);
            if (divide.compareTo(BigDecimal.valueOf(0.1)) < 0) {
                //校验通过
                resultMap.put("status", "通过");
            } else {
                //校验不通过
                resultMap.put("status", "不通过");
            }
        }
        resultMap.put("result", resultList);
        return resultMap;
    }
//    private Map<String, Object> getFactor(BigDecimal[][] bigDecimals) {
//        Map<String, Object> resultMap = new HashMap<>(2);
//        List<BigDecimal> resultList = new ArrayList<>(5);
//        if (bigDecimals.length == 1) {
//            resultList.add(BigDecimal.ONE);
//        } else {
//            //当bigDecimals.length>=2时
//            List<BigDecimal> list = new ArrayList<>(bigDecimals.length);
//            BigDecimal b1 = BigDecimal.ZERO;
//            BigDecimal sum = BigDecimal.ZERO;
//            BigDecimal temp = BigDecimal.ZERO;
//            int t = 0;
//            int y = 0;
//            int tt = 1;
//            int jj = 0;
//            for (int i = 0; i < bigDecimals.length; i++) {
//                temp = bigDecimals[y][t];
//                BigDecimal centerResult = BigDecimal.ZERO;
//                for (; jj < bigDecimals.length; jj++) {
//                    centerResult = centerResult.add(bigDecimals[jj][i]);
//                }
//                BigDecimal newResult = (temp.divide(centerResult, 12, BigDecimal.ROUND_HALF_UP));
//                b1 = b1.add(newResult);
//                if (t == bigDecimals.length - 1) {
//                    t = 0;
//                    ++y;
//                    if(tt<bigDecimals.length){
//                        i = -1;
//                    }
//                    list.add(b1);
//                    sum = sum.add(b1);
//                    b1 = BigDecimal.ZERO;
//                    tt++;
//                }else{
//                    t++;
//                }
//            }
//            if (list.size() > 0) {
//                for (int i = 0; i < list.size(); i++) {
//                    BigDecimal c1 = list.get(i).divide(sum, 12, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(list.size()), 12,
//                            BigDecimal.ROUND_HALF_UP);
//                    resultList.add(c1);
//                }
//            }
//            List<BigDecimal> awList = new ArrayList<>();
//            if (bigDecimals.length >= 3) {
//                int z = 0;
//                BigDecimal aw = BigDecimal.ZERO;
//                for (int i = 0; i < bigDecimals.length; i++) {
//                    for (int j = 0; j < bigDecimals.length; j++) {
//                        BigDecimal tempVal = bigDecimals[i][j];
//                        aw = aw.add(tempVal.multiply(resultList.get(z)));
//                    }
//                    if (z < resultList.size()-1) {
//                        z++;
//                    }
//                    awList.add(aw);
//                    aw = BigDecimal.ZERO;
//                }
//            }
//            int I = 0;
//            BigDecimal lamdaCenter = BigDecimal.ZERO;
//            BigDecimal lamda = BigDecimal.ZERO;
//            if (awList.size() > 0) {
//                for (BigDecimal k : awList) {
//                    lamdaCenter = lamdaCenter.add(k.divide(resultList.get(I), 12, RoundingMode.HALF_DOWN));
//                    I++;
//                }
//                lamda = lamdaCenter.divide(BigDecimal.valueOf(bigDecimals.length), 12, RoundingMode.HALF_DOWN);
//                BigDecimal CI = lamda.subtract(BigDecimal.valueOf(bigDecimals.length)).divide((BigDecimal.valueOf(bigDecimals.length).subtract(BigDecimal.ONE)), 12, RoundingMode.HALF_DOWN);
//                BigDecimal ri = getRi(bigDecimals.length);
//                BigDecimal divide = CI.divide(ri, 12, RoundingMode.HALF_DOWN);
//                if (divide.compareTo(BigDecimal.valueOf(0.1)) < 0) {
//                    //校验通过
//                    resultMap.put("status", "通过");
//                } else {
//                    //校验不通过
//                    resultMap.put("status", "不通过");
//                }
//            }
//        }
//        resultMap.put("result", resultList);
//        return resultMap;
//    }

    private BigDecimal getRi(int num) {
        switch (String.valueOf(num)) {
            case "3":
                return BigDecimal.valueOf(0.58);
            case "4":
                return BigDecimal.valueOf(0.90);
            case "5":
                return BigDecimal.valueOf(1.12);
            case "6":
                return BigDecimal.valueOf(1.24);
            case "7":
                return BigDecimal.valueOf(1.32);
            case "8":
                return BigDecimal.valueOf(1.41);
            case "9":
                return BigDecimal.valueOf(1.52);
            default:
                return BigDecimal.ZERO;
        }
    }

    private Map<String, BigDecimal[][]> getBigDecimals(Ahp ahp) {
        Map<String, BigDecimal[][]> map = new HashMap<>();
        //致灾因子1：土层年代-土层年代分类
        BigDecimal[][] abigDecimals = {{BigDecimal.ONE, ahp.getOneNum12Up().divide(ahp.getOneNum12Down(), 4, BigDecimal.ROUND_UP)
                , ahp.getOneNum13Up().divide(ahp.getOneNum13Down(), 4, BigDecimal.ROUND_UP)
                , ahp.getOneNum14Up().divide(ahp.getOneNum14Down(), 4, BigDecimal.ROUND_UP)},
                {ahp.getOneNum12Down().divide(ahp.getOneNum12Up(), 4, BigDecimal.ROUND_UP), BigDecimal.ONE
                        , ahp.getOneNum23Up().divide(ahp.getOneNum23Down(), 4, BigDecimal.ROUND_UP),
                        ahp.getOneNum24Up().divide(ahp.getOneNum24Down(), 4, BigDecimal.ROUND_UP)},
                {ahp.getOneNum13Down().divide(ahp.getOneNum13Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getOneNum23Down().divide(ahp.getOneNum23Up(), 4, BigDecimal.ROUND_UP)
                        , BigDecimal.ONE,
                        ahp.getOneNum34Up().divide(ahp.getOneNum34Down(), 4, BigDecimal.ROUND_UP)},
                {ahp.getOneNum14Down().divide(ahp.getOneNum14Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getOneNum24Down().divide(ahp.getOneNum24Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getOneNum34Down().divide(ahp.getOneNum34Up(), 4, BigDecimal.ROUND_UP),
                        BigDecimal.ONE}};
        map.put("土层年代", abigDecimals);
        //致灾因子2：综合地形指数-综合地形指数分类
        BigDecimal[][] bbigDecimals = {{BigDecimal.ONE, ahp.getTwoNum12Up().divide(ahp.getTwoNum12Down(), 4, BigDecimal.ROUND_UP)
                , ahp.getTwoNum13Up().divide(ahp.getTwoNum13Down(), 4, BigDecimal.ROUND_UP)
                , ahp.getTwoNum14Up().divide(ahp.getTwoNum14Down(), 4, BigDecimal.ROUND_UP)
                , ahp.getTwoNum15Up().divide(ahp.getTwoNum15Down(), 4, BigDecimal.ROUND_UP)
        },
                {ahp.getTwoNum12Down().divide(ahp.getTwoNum12Up(), 4, BigDecimal.ROUND_UP), BigDecimal.ONE
                        , ahp.getTwoNum23Up().divide(ahp.getTwoNum23Down(), 4, BigDecimal.ROUND_UP),
                        ahp.getTwoNum24Up().divide(ahp.getTwoNum24Down(), 4, BigDecimal.ROUND_UP)
                        , ahp.getTwoNum25Up().divide(ahp.getTwoNum25Down(), 4, BigDecimal.ROUND_UP)
                },
                {ahp.getTwoNum13Down().divide(ahp.getTwoNum13Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getTwoNum23Down().divide(ahp.getTwoNum23Up(), 4, BigDecimal.ROUND_UP)
                        , BigDecimal.ONE,
                        ahp.getTwoNum34Up().divide(ahp.getTwoNum34Down(), 4, BigDecimal.ROUND_UP)
                        , ahp.getTwoNum35Up().divide(ahp.getTwoNum35Down(), 4, BigDecimal.ROUND_UP)
                },
                {ahp.getTwoNum14Down().divide(ahp.getTwoNum14Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getTwoNum24Down().divide(ahp.getTwoNum24Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getTwoNum34Down().divide(ahp.getTwoNum34Up(), 4, BigDecimal.ROUND_UP),
                        BigDecimal.ONE,
                        ahp.getTwoNum45Up().divide(ahp.getTwoNum45Down(), 4, BigDecimal.ROUND_UP)
                },
                {ahp.getTwoNum15Down().divide(ahp.getTwoNum15Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getTwoNum25Down().divide(ahp.getTwoNum25Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getTwoNum35Down().divide(ahp.getTwoNum35Up(), 4, BigDecimal.ROUND_UP),
                        ahp.getTwoNum45Down().divide(ahp.getTwoNum45Up(), 4, BigDecimal.ROUND_UP),
                        BigDecimal.ONE}};
        map.put("综合地形指数", bbigDecimals);
        //致灾因子3：地震动峰值加速度参数-地震动参数分类
        BigDecimal[][] cbigDecimals = {
                {BigDecimal.ONE, ahp.getThreeNum12Up().divide(ahp.getThreeNum12Down(), 4, BigDecimal.ROUND_UP)},
                {ahp.getThreeNum12Down().divide(ahp.getThreeNum12Up(), 4, BigDecimal.ROUND_UP), BigDecimal.ONE}
        };
        map.put("地震动参数", cbigDecimals);
        //致灾因子4：距河流距离-距河流距离分类
        BigDecimal[][] dbigDecimals = {{BigDecimal.ONE, ahp.getFourNum12Up().divide(ahp.getFourNum12Down(), 4, BigDecimal.ROUND_UP)
                , ahp.getFourNum13Up().divide(ahp.getFourNum13Down(), 4, BigDecimal.ROUND_UP)
                , ahp.getFourNum14Up().divide(ahp.getFourNum14Down(), 4, BigDecimal.ROUND_UP)
                , ahp.getFourNum15Up().divide(ahp.getFourNum15Down(), 4, BigDecimal.ROUND_UP)
        },
                {ahp.getFourNum12Down().divide(ahp.getFourNum12Up(), 4, BigDecimal.ROUND_UP), BigDecimal.ONE
                        , ahp.getFourNum23Up().divide(ahp.getFourNum23Down(), 4, BigDecimal.ROUND_UP),
                        ahp.getFourNum24Up().divide(ahp.getFourNum24Down(), 4, BigDecimal.ROUND_UP)
                        , ahp.getFourNum25Up().divide(ahp.getFourNum25Down(), 4, BigDecimal.ROUND_UP)
                },
                {ahp.getFourNum13Down().divide(ahp.getFourNum13Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getFourNum23Down().divide(ahp.getFourNum23Up(), 4, BigDecimal.ROUND_UP)
                        , BigDecimal.ONE,
                        ahp.getFourNum34Up().divide(ahp.getFourNum34Down(), 4, BigDecimal.ROUND_UP)
                        , ahp.getFourNum35Up().divide(ahp.getFourNum35Down(), 4, BigDecimal.ROUND_UP)
                },
                {ahp.getFourNum14Down().divide(ahp.getFourNum14Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getFourNum24Down().divide(ahp.getFourNum24Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getFourNum34Down().divide(ahp.getFourNum34Up(), 4, BigDecimal.ROUND_UP),
                        BigDecimal.ONE,
                        ahp.getFourNum45Up().divide(ahp.getFourNum45Down(), 4, BigDecimal.ROUND_UP)
                },
                {ahp.getFourNum15Down().divide(ahp.getFourNum15Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getFourNum25Down().divide(ahp.getFourNum25Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getFourNum35Down().divide(ahp.getFourNum35Up(), 4, BigDecimal.ROUND_UP),
                        ahp.getFourNum45Down().divide(ahp.getFourNum45Up(), 4, BigDecimal.ROUND_UP),
                        BigDecimal.ONE}};
        map.put("距河流距离", dbigDecimals);
        //致灾因子5：场地类别-场地类别分类
        BigDecimal[][] ebigDecimals = {
                {BigDecimal.ONE, ahp.getFiveNum12Up().divide(ahp.getFiveNum12Down(), 4, BigDecimal.ROUND_UP), ahp.getFiveNum13Up().divide(ahp.getFiveNum13Down(), 4, BigDecimal.ROUND_UP), ahp.getFiveNum14Up().divide(ahp.getFiveNum14Down(), 4, BigDecimal.ROUND_UP)},
                {ahp.getFiveNum12Down().divide(ahp.getFiveNum12Up(), 4, BigDecimal.ROUND_UP), BigDecimal.ONE, ahp.getFiveNum23Up().divide(ahp.getFiveNum23Down(), 4, BigDecimal.ROUND_UP), ahp.getFiveNum24Up().divide(ahp.getFiveNum24Down(), 4, BigDecimal.ROUND_UP)},
                {ahp.getFiveNum13Down().divide(ahp.getFiveNum13Up(), 4, BigDecimal.ROUND_UP), ahp.getFiveNum23Down().divide(ahp.getFiveNum23Up(), 4, BigDecimal.ROUND_UP), BigDecimal.ONE,ahp.getFiveNum34Up().divide(ahp.getFiveNum34Down(), 4, BigDecimal.ROUND_UP)},
                {ahp.getFiveNum14Down().divide(ahp.getFiveNum14Up(), 4, BigDecimal.ROUND_UP), ahp.getFiveNum24Down().divide(ahp.getFiveNum24Up(), 4, BigDecimal.ROUND_UP),ahp.getFiveNum34Down().divide(ahp.getFiveNum34Up(), 4, BigDecimal.ROUND_UP), BigDecimal.ONE}
        };
        map.put("场地类别", ebigDecimals);
        //砂土液化危险性评价
        BigDecimal[][] fbigDecimals = {{BigDecimal.ONE, ahp.getSixNum12Up().divide(ahp.getSixNum12Down(), 4, BigDecimal.ROUND_UP)
                , ahp.getSixNum13Up().divide(ahp.getSixNum13Down(), 4, BigDecimal.ROUND_UP)
                , ahp.getSixNum14Up().divide(ahp.getSixNum14Down(), 4, BigDecimal.ROUND_UP)
                , ahp.getSixNum15Up().divide(ahp.getSixNum15Down(), 4, BigDecimal.ROUND_UP)
        },
                {ahp.getSixNum12Down().divide(ahp.getSixNum12Up(), 4, BigDecimal.ROUND_UP), BigDecimal.ONE
                        , ahp.getSixNum23Up().divide(ahp.getSixNum23Down(), 4, BigDecimal.ROUND_UP),
                        ahp.getSixNum24Up().divide(ahp.getSixNum24Down(), 4, BigDecimal.ROUND_UP)
                        , ahp.getSixNum25Up().divide(ahp.getSixNum25Down(), 4, BigDecimal.ROUND_UP)
                },
                {ahp.getSixNum13Down().divide(ahp.getSixNum13Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getSixNum23Down().divide(ahp.getSixNum23Up(), 4, BigDecimal.ROUND_UP)
                        , BigDecimal.ONE,
                        ahp.getSixNum34Up().divide(ahp.getSixNum34Down(), 4, BigDecimal.ROUND_UP)
                        , ahp.getSixNum35Up().divide(ahp.getSixNum35Down(), 4, BigDecimal.ROUND_UP)
                },
                {ahp.getSixNum14Down().divide(ahp.getSixNum14Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getSixNum24Down().divide(ahp.getSixNum24Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getSixNum34Down().divide(ahp.getSixNum34Up(), 4, BigDecimal.ROUND_UP),
                        BigDecimal.ONE,
                        ahp.getSixNum45Up().divide(ahp.getSixNum45Down(), 4, BigDecimal.ROUND_UP)
                },
                {ahp.getSixNum15Down().divide(ahp.getSixNum15Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getSixNum25Down().divide(ahp.getSixNum25Up(), 4, BigDecimal.ROUND_UP)
                        , ahp.getSixNum35Down().divide(ahp.getSixNum35Up(), 4, BigDecimal.ROUND_UP),
                        ahp.getSixNum45Down().divide(ahp.getSixNum45Up(), 4, BigDecimal.ROUND_UP),
                        BigDecimal.ONE}};
        map.put("砂土液化危险性评价", fbigDecimals);
        return map;
    }

    /**
     * 删除并保存层次分析法的最终结果 操作同一张表，传递不同的参数
     */
    private void deleteAndSaveFinalResult(Ahp ahp) {
        String userId = PlatformSessionContext.getUserID();
        String fina = "";
        //2是最终结果 1是中间结果
        if("2".equals(ahp.getResultStatus())){
            //判断任务是否存在最终结果如果存在则删除同时新增一条最终结果
//            DzzhModelSandLiquefaction modelSand = sandLiquefactionRepository.getModelSandLiquefaction(ahp.getTaskId(), "2");
//            if(modelSand!=null){
                sandLiquefactionRepository.delResult(ahp.getDmslId());
//            }
            fina+= ResultEnum.FINA.getState();
        }else{
            sandLiquefactionRepository.delResult(ahp.getDmslId());
            sandLiquefactionRepository.deleteAhpResult(ahp.getDmslId());
            fina+= ResultEnum.CENTER.getState();
        }
        //删除计算结果数据
        sandLiquefactionRepository.deleteAhpResult(ahp.getDmslId());


        //sandLiquefactionRepository.delFinalResultByTaskId(ahp.getTaskId(), userId);
        String dmslId = ahp.getDmslId();
        DzzhModelSandLiquefaction modelSandLiquefaction = new DzzhModelSandLiquefaction();
        modelSandLiquefaction.setDmslId(dmslId).setTaskId(ahp.getTaskId())
                .setLithologyVersion(ahp.getLithologyVersion()).setAlgorithmType("3")
                .setAltitudeVersion(ahp.getAltitudeVersion()).setA1Version(ahp.getA1Version()).setA2Version(ahp.getA2Version()).setA3Version(ahp.getA3Version())
                .setOperands("3").setResultStatus(fina);

        modelSandLiquefaction.setEvaluateUser(userId);
        modelSandLiquefaction.setEvaluateTime(new Date());
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        modelSandLiquefaction.setEvaluateUserName(sUser.getUserName());
        modelSandLiquefaction.setCreateUser(userId);
        modelSandLiquefaction.setCreateTime(new Date());
        modelSandLiquefaction.setCreateUserName(sUser.getUserName());
        modelSandLiquefaction.setDelFlag(YNEnum.N.toString());
        modelSandLiquefaction.setSelectedMatrix(ahp.getSelectedMatrix());
        sandLiquefactionRepository.saveFinalResult(modelSandLiquefaction);
    }

    /**
     * 删除标贯法和液化指数法的最终结果 操作同一张表，传递不同的参数
     */
    private void saveResult(EvaluateParam param, String dmslId, String canShow) {
        String userId = PlatformSessionContext.getUserID();
        //判断是否存在结果如果存在则删除同时新增一条结果
        //sandLiquefactionRepository.delFinalResultByTaskId(param.getTaskId(), userId);
        DzzhModelSandLiquefaction modelSandLiquefaction = new DzzhModelSandLiquefaction();
        modelSandLiquefaction.setDmslId(dmslId).setTaskId(param.getTaskId())
                .setDrillVersion(param.getVersionCode()).setAlgorithmType(param.getAlgorithmType())
                .setOperands(param.getOperands()).setModelType(param.getModelType()).setEarthquakeGroup(param.getEarthquakeGroup())
                .setAdjustFactor(param.getAdjustFactor()).setResultStatus(param.getResultStatus());
        modelSandLiquefaction.setEvaluateUser(userId);
        modelSandLiquefaction.setEvaluateTime(new Date());
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        modelSandLiquefaction.setEvaluateUserName(sUser.getUserName());
        modelSandLiquefaction.setCreateUser(userId);
        modelSandLiquefaction.setCreateTime(new Date());
        modelSandLiquefaction.setDelFlag(YNEnum.N.toString());
        modelSandLiquefaction.setDataFrom(param.getDataFrom());
        modelSandLiquefaction.setCreateUserName(sUser.getUserName());
        modelSandLiquefaction.setCanShow(canShow);
        sandLiquefactionRepository.saveFinalResult(modelSandLiquefaction);
    }

    //获取钻孔2数据
    private List<JSONObject> getDrill02(EvaluateParam param){
        List<JSONObject> y02List = redisTemplate.opsForList().range(RedisKeyConstants.SYSTEMPREFIX + ":drill:02:" + param.getTaskId() + ":" + param.getVersionCode(), 0, -1);
        if (PlatformObjectUtils.isEmpty(y02List) && y02List.size()==0) {
            //redis无钻孔信息，远程调用基础数据系统的钻孔信息
            Map<String, Object> drillMap = this.setRedis(param.getVersionCode(), param.getTaskId());
            return (List<JSONObject>) drillMap.get("02");
        }
        return y02List;
    }
    //从redis中获取钻孔子表数据
    private List getChildDrillData(String taskId,String versionCode,String id,String child){
        return redisTemplate.opsForList().range(
                RedisKeyConstants.SYSTEMPREFIX + ":drill:" + ":" + taskId + ":" + versionCode + ":" + id + ":"+child, 0, -1);
    }

    //液化判别标准贯入锤击数基准
    private  List<BigDecimal> getBlowCount(String operands){
        List<BigDecimal> blowCount = new ArrayList<>();
        if (operands.equals(String.valueOf(OperandsEnum.SANDSILT.getState()))) {
            blowCount = getSoilNumList();
        } else {
            blowCount = getLoessNumList();
        }
        return blowCount;
    }

    /**
     * 相同地震动加速度和地下水位深度下的同一钻孔编号，只要有一个标贯点液化了则相同地震动加速度和地下水位深度下的钻孔液化，如果该钻孔在其他的地震动加速度、地下水位
     * 深度下也存在，是否液化取决于那个地震动加速度、水位深度下的标贯点是否液化
     */
    private void getAndSaveByModelType(String dmslId,EvaluateParam param) {
        Integer modelType = param.getModelType();
        String versionCode = param.getVersionCode();
        String taskId = param.getTaskId();
        //调整系数，设计地震第一组取0.80，第二组取0.95，第三组取1.05。
        BigDecimal retioβ = getRetioβByEarthquakeGroup(param.getEarthquakeGroup());

        Map<String, List<DzzhResultDetailSandLiquefaction>> drillMap = new HashMap<>();
        Map<String, String> codeMap = new HashMap<>();

        //1表示使用的是从基础数据处获取到的钻孔信息
        if (param.getDataFrom() == 1) {
            //从redis取出钻孔y02数据和关联的y04、05和10的数据
            List<JSONObject> drill02List = getDrill02(param);
            //1表示使用从基础数据选择的钻孔数据，需要查询钻孔数据表Y02、同时关联Y04、Y05和Y10
            if (PlatformObjectUtils.isNotEmpty(drill02List)) {
                // 液化判别标准贯入锤击数基准
                for (JSONObject drill02JSON : drill02List) {
                    //黏粒含量ρc
                    BigDecimal pc = getPc(taskId, versionCode,drill02JSON.getString("id"));
                    // y02的id，根据id查询个子表的数据
                    String id = (String) drill02JSON.get("id");
                    List<JSONObject> list05 = new ArrayList<>();
                    //从redis中获取02对应id关联的05的数据
                    List y05List = getChildDrillData(taskId,versionCode,id,"JcRfcpY05");
                    //从redis中获取02对应id关联的04的数据
                    List y04List = getChildDrillData(taskId,versionCode,id,"JcRfcpY04");

                    // 每一个钻孔标准贯人试验点的总数,用于液化指数时计算
                    // 液化判别地下水位深度(稳定水位深度)
                    Object dw = drill02JSON.get("stableWaterDepth");
                    // 经纬度
                    Object longitudeObj = drill02JSON.get("longitude");
                    Object latitudeObj = drill02JSON.get("latitude");
                    List<BigDecimal> dwList = new ArrayList<>();
                    // --地下水位深度(m); 为非0时分别计算非0值和0，如果为0时只计算0
                    dwList.add(new BigDecimal(dw.toString()));
                    if (new BigDecimal(dw.toString()).compareTo(new BigDecimal(0)) > 0) {
                        dwList.add(new BigDecimal(0));
                    }
                    if (PlatformObjectUtils.isNotEmpty(y05List)) {
                        // 第一个标贯点的前一个标贯点的设置为0
                        BigDecimal topDepth = BigDecimal.ZERO;
                        // 根据层底深度获取在这层底深度中的所有的标贯点，包括di和hi的信息
                        for (Object json04 : y04List) {
                            JSONObject jsonObject04 = (JSONObject) json04;
                            //层底深度
                            BigDecimal bottomDepth = new BigDecimal(jsonObject04.get("bottom_depth").toString());
                            List<JSONObject> jsonObject05List = new ArrayList<>();
                            for (BigDecimal dwBigDecimal : dwList) {
                                jsonObject05List = getAllPenetrationPointByBottomDepth(bottomDepth, y05List, topDepth, dwBigDecimal, param.getAdjustFactor());
                                list05.addAll(jsonObject05List);
                            }
                            topDepth = BigDecimal.valueOf((Double) jsonObject04.get("bottom_depth"));
                        }
                    }
                    List<DzzhResultDetailSandLiquefaction> drslList = new ArrayList<>();
                    // 计算单个标贯试验点的液化指数，相加得到单个钻孔的液化指数
                    //BigDecimal sumIle = BigDecimal.ZERO;
                    if (PlatformObjectUtils.isNotEmpty(list05)) {
                        Map<BigDecimal,JSONObject> dsMap = new HashMap<>();
                        for (BigDecimal count : getBlowCount(param.getOperands())) {
                            List<DzzhResultDetailSandLiquefaction> finalList = new ArrayList<>();
                            List<DzzhResultDetailSandLiquefaction> zeroFinalList = new ArrayList<>();
                            BigDecimal sumIle = BigDecimal.ZERO;
                            BigDecimal zeroSumIle = BigDecimal.ZERO;
                            BigDecimal ile = BigDecimal.ZERO;
                            BigDecimal zeroIle = BigDecimal.ZERO;
                            for (JSONObject jsonObject05 : list05) {
                                //标贯点默认不液化
                                AtomicBoolean bgdIsLique = new AtomicBoolean(false);
                                // 地震动加速度
                                BigDecimal earthquakeAcceleration = getEarthquakeAcceleration(param.getOperands(), count);
                                // 标贯点顶深
                                BigDecimal standardStartDepth = jsonObject05.getBigDecimal("standard_start_depth");
                                // 标贯点底深
                                BigDecimal standardEndDepth = jsonObject05.getBigDecimal("standard_end_depth");
                                // 标贯值即实际锤击数N
                                BigDecimal standardNumber = new BigDecimal((Integer) jsonObject05.get("standard_number"));
                                // 标贯点深度
                                BigDecimal ds = (standardStartDepth.add(standardEndDepth)).divide(new BigDecimal(2), 2);
                                // 获取地层编号、底层深度、分层厚度、岩土名称（y04和y05没有直接联系，需要判断在这个深度下的y04数据）
                                JSONObject jsonObj4 = new JSONObject();
                                if(dsMap.containsKey(ds)){
                                    jsonObj4 = dsMap.get(ds);
                                }else{
                                    jsonObj4 = getJcRfcpY04Data(y04List, ds);
                                    dsMap.put(ds,jsonObj4);
                                }
                                BigDecimal dwt = (BigDecimal) jsonObject05.get("dw");
                                // 当模型选择的是建筑抗震设计规范、或选择了区域性地震安全性评价技术规范但深度在0-10范围内的，或者选择了液化指数模型（此时不区分砂土粉土和黄土）
                                if ((modelType!=null && modelType == 1) || (modelType!=null && modelType == 2 && ds.compareTo(new BigDecimal(10)) < 0) || "2".equals(param.getAlgorithmType()) || (modelType==null && ds.compareTo(new BigDecimal(20)) < 0)) {
                                    // 公式1建筑抗震设计规范 或模型是区域性地震安全性评价技术规范但在地面下10m深度范围内
                                    BigDecimal lnTemp = (new BigDecimal(0.6).multiply(ds).add(new BigDecimal(1.5)));
                                    Double lnResult = Math.log(lnTemp.doubleValue());
                                    BigDecimal dwTemp = dwt.multiply(new BigDecimal(0.1));
                                    BigDecimal centerResult = new BigDecimal(lnResult).subtract(dwTemp);
                                    BigDecimal prefixResult = count.multiply(retioβ).multiply(centerResult);
                                    BigDecimal sqrtTemp = new BigDecimal(3).divide(pc, 2, RoundingMode.DOWN);
                                    BigDecimal sqrtResult = BigDecimal.valueOf(Math.sqrt(sqrtTemp.doubleValue()));
                                    BigDecimal ncr = prefixResult.multiply(sqrtResult);
                                    BigDecimal divide = standardNumber.divide(ncr, 2, RoundingMode.HALF_DOWN);
                                    if (divide.compareTo(new BigDecimal(1)) <= 0) {
                                        // 大于1则该层标贯试验点为不液化，小于等于1则液化
                                        bgdIsLique.set(true);
                                        //只要存在一个标贯点液化，则整个钻孔液化
                                    }
                                    // 液化指数法
                                    if ("2".equals(param.getAlgorithmType())) {
                                        //BigDecimal ile = BigDecimal.ZERO;
                                        // 获取钻孔下的标贯点且标贯点的标贯点深度在液化判别深度内的才计算液化指数ile。
                                        if (standardEndDepth.compareTo(param.getAdjustFactor()) <= 0) {
                                            BigDecimal divideValue = BigDecimal.valueOf(1);
                                            // 实测值除临界值的值A如果A大于等于1则比值取1，比值小于0，比如0.2，那取值0.2
                                            if (divide.compareTo(BigDecimal.valueOf(1)) < 0) {
                                                divideValue = divide;
                                            } else {
                                                divideValue = BigDecimal.ONE;
                                            }
                                            BigDecimal firstDivide = BigDecimal.ONE.subtract(divideValue);
                                            BigDecimal di = (BigDecimal) jsonObject05.get("d1");
                                            BigDecimal h1 = (BigDecimal) jsonObject05.get("h1");
                                            BigDecimal wi = BigDecimal.ZERO;
                                            // 当该层中点深度hi不大于5m时应采用10，等于20m时应采用零值，5~20m时应按线性内插法取值。
                                            if (h1.compareTo(BigDecimal.valueOf(9999)) == 0) {
                                                wi = BigDecimal.ZERO;
                                                h1 = BigDecimal.ZERO;
                                            } else {
                                                if (h1.compareTo(new BigDecimal(5)) <= 0) {
                                                    wi = BigDecimal.valueOf(10);
                                                } else if (h1.compareTo(new BigDecimal(20)) == 0) {
                                                    wi = BigDecimal.ZERO;
                                                } else if (h1.compareTo(new BigDecimal(5)) > 0 && h1.compareTo(new BigDecimal(20)) < 0) {
                                                    // 线性内插法求值 线性内插法公式是Y=Y1+（Y2-Y1）×（X-X1）／（X2-X1）
                                                    // x处于x1和x2之间，y处于y1和y2之间
                                                    BigDecimal fdivide = (BigDecimal.ZERO.subtract(BigDecimal.valueOf(10))).
                                                            divide(new BigDecimal(20).subtract(new BigDecimal(5)), 2, RoundingMode.HALF_DOWN);
                                                    wi = BigDecimal.valueOf(10).add(fdivide.multiply(h1.subtract(new BigDecimal(5))));
                                                }
                                            }
                                            if(dwt.compareTo(BigDecimal.ZERO)==0){
                                                zeroIle = firstDivide.multiply(di).multiply(wi);
                                            }else{
                                                ile = firstDivide.multiply(di).multiply(wi);
                                            }
                                            //ile = firstDivide.multiply(di).multiply(wi);
                                            String sandLevel = getSandLevel(ile);
                                            String drslId = UUIDGenerator.getUUID();
                                            DzzhResultDetailSandLiquefaction resultDetailSandLiquefaction = DzzhResultDetailSandLiquefaction.builder()
                                                    .drslId(drslId).dmslId(dmslId).earthquakeAcceleration(earthquakeAcceleration)
                                                    .groundWaterDepth(dwt).longitude(new BigDecimal(longitudeObj.toString()))
                                                    .latitude(new BigDecimal(latitudeObj.toString())).liquefactionGroundWaterDepth(dwt)
                                                    .adjustFactor(retioβ).drillCode((String) drill02JSON.get("drillCode"))
                                                    .stratumNum((String) jsonObj4.get("assise_number")).stratumDepth(new BigDecimal((Double) jsonObj4.get("bottom_depth")))
                                                    .layerThickness(new BigDecimal((Double) jsonObj4.get("layer_thickness")))
                                                    .geotechnicalName((String) jsonObj4.get("geotechnical_name")).fullboreTopDepth(standardStartDepth)
                                                    .fullboreBottomDepth(standardEndDepth).clayContent(pc.toString()).algorithmType(param.getAlgorithmType())
                                                    .ncr(ncr).actualBlowsNumber(new BigDecimal((Integer) jsonObject05.get("standard_number")))
                                                    .drillLiquefactionDifferentiate("0").specificValue(divide)
                                                    .liquefactionDifferentiate(bgdIsLique.get() ? "1" : "0").taskId(taskId).delFlag(YNEnum.N.toString())
                                                    .fullboreSoilDepth(h1).fullboreSoilThickness(di).wi(wi).ei(ile).ds(ds).sandLevel(sandLevel)
                                                    .geom("POINT("+new BigDecimal(longitudeObj.toString())+" "+new BigDecimal(latitudeObj.toString())+")")
                                                    .build();
                                            //sumIle = sumIle.add(ile);
                                            //drslList.add(resultDetailSandLiquefaction);
                                            if(dwt.compareTo(BigDecimal.ZERO)==0){
                                                zeroSumIle = zeroSumIle.add(zeroIle);
                                                zeroFinalList.add(resultDetailSandLiquefaction);
                                            }else{
                                                sumIle = sumIle.add(ile);
                                                finalList.add(resultDetailSandLiquefaction);
                                            }
                                            //获取相同地震动加速度、地下水位深度的钻孔（非标贯点数据）数据
                                            //getDrillMap(drillMap, codeMap, earthquakeAcceleration, dwt, resultDetailSandLiquefaction);
                                        }
                                    }
                                    // 标贯法
                                    if (!"2".equals(param.getAlgorithmType())) {
                                        DzzhResultDetailSandLiquefaction resultDetailSandLiquefaction =
                                                DzzhResultDetailSandLiquefaction.builder()
                                                        .drslId(UUIDGenerator.getUUID()).dmslId(dmslId).earthquakeAcceleration(earthquakeAcceleration)
                                                        .groundWaterDepth(dwt).longitude(new BigDecimal(longitudeObj.toString())).latitude(new BigDecimal(latitudeObj.toString()))
                                                        .liquefactionGroundWaterDepth(dwt).adjustFactor(retioβ).drillCode((String) drill02JSON.get("drillCode"))
                                                        .stratumNum((String) jsonObj4.get("assise_number")).stratumDepth(new BigDecimal((Double) jsonObj4.get("bottom_depth")))
                                                        .layerThickness(new BigDecimal((Double) jsonObj4.get("layer_thickness"))).geotechnicalName((String) jsonObj4.get("geotechnical_name"))
                                                        .fullboreTopDepth(standardStartDepth).fullboreBottomDepth(standardEndDepth).clayContent(pc.toString())
                                                        .ncr(ncr).actualBlowsNumber(new BigDecimal((Integer) jsonObject05.get("standard_number")))
                                                        .drillLiquefactionDifferentiate( "0").specificValue(divide).ds(ds).algorithmType(param.getAlgorithmType())
                                                        .liquefactionDifferentiate(bgdIsLique.get() ? "1" : "0").taskId(taskId).delFlag(YNEnum.N.toString())
                                                        .geom("POINT("+new BigDecimal(longitudeObj.toString())+" "+new BigDecimal(latitudeObj.toString())+")")
                                                        .build();
//                                        drslList.add(resultDetailSandLiquefaction);
//                                        //获取相同地震动加速度、地下水位深度的钻孔（非标贯点数据）数据
//                                        getDrillMap(drillMap, codeMap, earthquakeAcceleration, dwt, resultDetailSandLiquefaction);
                                        finalList.add(resultDetailSandLiquefaction);
                                    }
                                }else if(modelType == 2 && (ds.compareTo(new BigDecimal(10)) >= 0 && ds.compareTo(new BigDecimal(30)) <= 0)){
                                    // 公式2区域性地震安全性评价技术规范同时地面下10m-30m深度范围内
                                    // 工作等级系数
                                    BigDecimal r = BigDecimal.valueOf(1.0);
                                    BigDecimal firstDivide = (new BigDecimal(58).multiply(earthquakeAcceleration).divide((earthquakeAcceleration.
                                            add(new BigDecimal(0.4))), 2, RoundingMode.HALF_DOWN));
                                    BigDecimal firstSubtract = new BigDecimal(1).subtract(new BigDecimal(0.02).multiply(dwt));
                                    BigDecimal secondDivide = ds.divide(ds.add(new BigDecimal(6.2)), 2, RoundingMode.HALF_DOWN);
                                    BigDecimal addPart = new BigDecimal(0.27).add(secondDivide);
                                    BigDecimal sqrtTemp = new BigDecimal(3).divide(pc, 2, RoundingMode.HALF_DOWN);
                                    BigDecimal sqrtResult = BigDecimal.valueOf(Math.sqrt(sqrtTemp.doubleValue()));
                                    BigDecimal ncr = r.multiply(retioβ).multiply(firstDivide).multiply(firstSubtract).multiply(addPart).multiply(sqrtResult);
                                    BigDecimal divide = standardNumber.divide(ncr, 2, RoundingMode.DOWN);
                                    if (divide.compareTo(new BigDecimal(1)) <= 0) {
                                        // 大于1则该层标贯试验点为不液化，小于等于1则液化
                                        bgdIsLique.set(true);
                                    }
                                    DzzhResultDetailSandLiquefaction resultDetailSandLiquefaction =
                                            DzzhResultDetailSandLiquefaction.builder()
                                                    .drslId(UUIDGenerator.getUUID()).earthquakeAcceleration(earthquakeAcceleration).groundWaterDepth(dwt)
                                                    .longitude(new BigDecimal(longitudeObj.toString())).latitude(new BigDecimal(latitudeObj.toString()))
                                                    .liquefactionGroundWaterDepth(dwt).adjustFactor(param.getAdjustFactor()).drillCode((String) drill02JSON.get("drillCode"))
                                                    .stratumNum((String) jsonObj4.get("assise_number")).stratumDepth(new BigDecimal((Double) jsonObj4.get("bottom_depth")))
                                                    .layerThickness(new BigDecimal((Double) jsonObj4.get("layer_thickness"))).geotechnicalName((String) jsonObj4.get("geotechnical_name"))
                                                    .fullboreTopDepth(standardStartDepth).fullboreBottomDepth(standardEndDepth).clayContent(pc.toString())
                                                    .ncr(ncr).actualBlowsNumber(new BigDecimal((Integer) jsonObject05.get("standard_number")))
                                                    .drillLiquefactionDifferentiate( "0").specificValue(divide).ds(ds).algorithmType(param.getAlgorithmType())
                                                    .liquefactionDifferentiate(bgdIsLique.get() ? "1" : "0").taskId(taskId).delFlag(YNEnum.N.toString())
                                                    .geom("POINT("+new BigDecimal(longitudeObj.toString())+" "+new BigDecimal(latitudeObj.toString())+")")
                                                    .dmslId(dmslId)
                                                    .build();
                                    //drslList.add(resultDetailSandLiquefaction);
                                    finalList.add(resultDetailSandLiquefaction);
                                    //获取相同地震动加速度、地下水位深度的钻孔（非标贯点数据）数据
                                    //getDrillMap(drillMap, codeMap, earthquakeAcceleration, dwt, resultDetailSandLiquefaction);
                                }
                            }
                            if ("2".equals(param.getAlgorithmType())) {
                                saveResultDetailSandLiquefaction(finalList, sumIle);
                                saveResultDetailSandLiquefaction(zeroFinalList, zeroSumIle);
                            }else{
                                sandLiquefactionRepository.saveResultDetailSandLiquefaction(finalList);
                            }
                            if(finalList.size()>0){
                                drslList.addAll(finalList);
                            }
                            if(zeroFinalList.size()>0){
                                drslList.addAll(zeroFinalList);
                            }
                        }
                    }
//                    List<DzzhResultDetailSandLiquefaction> finalList = new ArrayList<>();
//                    if(PlatformObjectUtils.isNotEmpty(drslList)){
////                                long count = drslList.stream().filter(entity -> {
////                                    return "1".equals(entity.getLiquefactionDifferentiate());
////                                }).count();
////                                if(count>0){
////                                    drslList.forEach(entity->entity.setDrillLiquefactionDifferentiate("1"));
////                                }
//                        Map<String, List<DzzhResultDetailSandLiquefaction>> collect = drslList.stream().collect(Collectors.groupingBy(dzzhResultDetailSandLiquefaction -> {
//                            return dzzhResultDetailSandLiquefaction.getEarthquakeAcceleration() + "_" + dzzhResultDetailSandLiquefaction.getLiquefactionGroundWaterDepth();
//                        }));
//                        collect.forEach((k11,v11)->{
//                            long count = v11.stream().filter(entity -> {
//                                return "1".equals(entity.getLiquefactionDifferentiate());
//                            }).count();
//                            if(count>0){
//                                v11.forEach(entity->entity.setDrillLiquefactionDifferentiate("1"));
//                            }
//                            finalList.addAll(v11);
//                        });
//                    }
//                    saveResultDetailSandLiquefaction(finalList, sumIle);
                }
                //液化结果分布图，以钻孔点为圆心，以两口钻井间距的一半为半径的圆形判别为液化，其他区域为不液化，从而得到一个区域的液化评价结果。
                //getAndSaveSandCircle(drillMap, taskId);
            }
        } else {
            //2表示使用用户上传的数据
            List<SandLiquefactionDrill> drillList = sandLiquefactionRepository.getUploadDrillList(taskId, versionCode);
            List<BigDecimal> blowCount = null;
            if (param.getOperands().equals(String.valueOf(OperandsEnum.SANDSILT.getState()))) {
                blowCount = getSoilNumList();
            } else {
                blowCount = getLoessNumList();
            }
            List<BigDecimal> finalBlowCount = blowCount;
            if (drillList != null && drillList.size() > 0) {
                //液化指数法
                if("2".equals(param.getAlgorithmType())){
                    //钻孔的每一个层底深度中有多少标贯点
                    Map<String, List<SandLiquefactionDrill>> depthDrillList = drillList.stream().collect(Collectors.groupingBy(entity -> {
                        return entity.getDrillCode() + "_" + entity.getLongitude() + "_" + entity.getLatitude() + "_" + entity.getBottomDepth();
                    }));
                    //返回的map是包含d1、h1信息的以钻孔为单位的各个标贯点信息
                    Map<String, List<SandLiquefactionDrill>> map = getAllPenetrationPointByBottomDepth(depthDrillList, param.getAdjustFactor());
                    if(map.values().size()>0){
                        map.forEach((k,v)->{
                            for (BigDecimal count : finalBlowCount) {
                                List<DzzhResultDetailSandLiquefaction> finalList = new ArrayList<>();
                                List<DzzhResultDetailSandLiquefaction> zeroFinalList = new ArrayList<>();
                                //每个钻孔下的标贯点信息  k表示每个钻孔
                                BigDecimal sumIle = BigDecimal.ZERO;
                                BigDecimal zeroSumIle = BigDecimal.ZERO;
                                BigDecimal ile = BigDecimal.ZERO;
                                BigDecimal zeroIle = BigDecimal.ZERO;
                                for (SandLiquefactionDrill sandLiquefactionDrill : v) {
                                    //地震动加速度
                                    BigDecimal earthquakeAcceleration = getEarthquakeAcceleration(param.getOperands(), count);
                                    AtomicBoolean bgdIsLique = new AtomicBoolean(false);
                                    BigDecimal pc = sandLiquefactionDrill.getPc();
                                    //标贯值即实际锤击数N
                                    BigDecimal standardNumber = sandLiquefactionDrill.getRealityNum();
                                    //标贯点深度
                                    BigDecimal ds = sandLiquefactionDrill.getDs();
                                    //当模型选择的是建筑抗震设计规范、或选择了区域性地震安全性评价技术规范但深度在0-10范围内的，或者选择了液化指数模型（此时不区分砂土粉土和黄土）,或者选择标贯法的饱和黄土（地面下20m深度范围内）
                                    if ((modelType!=null && modelType == 1) || (modelType!=null && modelType == 2 && ds.compareTo(new BigDecimal(10)) < 0) || "2".equals(param.getAlgorithmType()) || (modelType==null && ds.compareTo(new BigDecimal(20)) < 0)) {
                                        //公式1建筑抗震设计规范 或模型是区域性地震安全性评价技术规范但在地面下10m深度范围内
                                        BigDecimal lnTemp = (new BigDecimal(0.6).multiply(ds).add(new BigDecimal(1.5)));
                                        Double lnResult = Math.log(lnTemp.doubleValue());
                                        BigDecimal dwTemp = sandLiquefactionDrill.getDw().multiply(new BigDecimal(0.1));
                                        BigDecimal centerResult = new BigDecimal(lnResult).subtract(dwTemp);
                                        BigDecimal prefixResult = count.multiply(retioβ).multiply(centerResult);
                                        BigDecimal sqrtTemp = new BigDecimal(3).divide(pc, 2, RoundingMode.DOWN);
                                        BigDecimal sqrtResult = BigDecimal.valueOf(Math.sqrt(sqrtTemp.doubleValue()));
                                        BigDecimal ncr = prefixResult.multiply(sqrtResult);
                                        BigDecimal divide = standardNumber.divide(ncr, 2, RoundingMode.HALF_DOWN);
                                        if (divide.compareTo(new BigDecimal(1)) <= 0) {
                                            //大于1则该层标贯试验点为不液化，小于等于1则液化
                                            bgdIsLique.set(true);
                                        }
                                        //液化指数法
                                        if ("2".equals(param.getAlgorithmType())) {
                                            //获取钻孔下的标贯点且标贯点的标贯点深度在液化判别深度内的才计算液化指数ile。
                                            if (ds.compareTo(param.getAdjustFactor()) <= 0) {
                                                BigDecimal divideValue = BigDecimal.valueOf(1);
                                                //实测值除临界值的值A如果A大于等于1则比值取1，比值小于0，比如0.2，那取值0.2
                                                if (divide.compareTo(BigDecimal.valueOf(1)) < 0) {
                                                    divideValue = divide;
                                                }
                                                BigDecimal firstDivide = new BigDecimal(1).subtract(divideValue);
                                                BigDecimal di = sandLiquefactionDrill.getD1();
                                                BigDecimal h1 = sandLiquefactionDrill.getH1();
                                                BigDecimal wi = BigDecimal.ZERO;
                                                //当该层中点深度hi不大于5m时应采用10，等于20m时应采用零值，5~20m时应按线性内插法取值。
                                                if (h1.compareTo(BigDecimal.valueOf(9999)) == 0) {
                                                    wi = BigDecimal.ZERO;
                                                    h1 = BigDecimal.ZERO;
                                                } else {
                                                    if (h1.compareTo(new BigDecimal(5)) <= 0) {
                                                        wi = BigDecimal.valueOf(10);
                                                    } else if (h1.compareTo(new BigDecimal(20)) == 0) {
                                                        wi = BigDecimal.ZERO;
                                                    } else if (h1.compareTo(new BigDecimal(5)) > 0 && h1.compareTo(new BigDecimal(20)) < 0) {
                                                        //线性内插法求值 线性内插法公式是Y=Y1+（Y2-Y1）×（X-X1）／（X2-X1）    x处于x1和x2之间，y处于y1和y2之间
                                                        BigDecimal fdivide = (BigDecimal.ZERO.subtract(BigDecimal.valueOf(10))).divide(new BigDecimal(20).subtract(new BigDecimal(5)), 2, RoundingMode.HALF_DOWN);
                                                        wi = BigDecimal.valueOf(10).add(fdivide.multiply(h1.subtract(new BigDecimal(5))));
                                                    }
                                                }
                                                //水位埋深不同采取不同的取值
                                                if(sandLiquefactionDrill.getDw().compareTo(BigDecimal.ZERO)==0){
                                                    zeroIle = firstDivide.multiply(di).multiply(wi);
                                                }else{
                                                    ile = firstDivide.multiply(di).multiply(wi);
                                                }
                                                String sandLevel = getSandLevel(ile);
                                                String drslId = UUIDGenerator.getUUID();
                                                //选择的是上传的数据，那么不保存标贯点顶深和低深
                                                DzzhResultDetailSandLiquefaction resultDetailSandLiquefaction
                                                        = DzzhResultDetailSandLiquefaction.builder()
                                                        .drslId(drslId).dmslId(dmslId)
                                                        .earthquakeAcceleration(earthquakeAcceleration).groundWaterDepth(sandLiquefactionDrill.getDw()).longitude(sandLiquefactionDrill.getLongitude())
                                                        .latitude(sandLiquefactionDrill.getLatitude()).liquefactionGroundWaterDepth(sandLiquefactionDrill.getDw()).adjustFactor(retioβ).drillCode(sandLiquefactionDrill.getDrillCode())
                                                        .stratumNum(sandLiquefactionDrill.getPointNum()).stratumDepth(sandLiquefactionDrill.getBottomDepth())
                                                        .layerThickness(sandLiquefactionDrill.getLayerThickness()).geotechnicalName(sandLiquefactionDrill.getGeotechnicalName())
                                                        .clayContent(pc.toString()).ncr(ncr).wi(wi).ei(ile).ds(ds).sandLevel(sandLevel).algorithmType(param.getAlgorithmType())
                                                        .actualBlowsNumber(sandLiquefactionDrill.getRealityNum()).drillLiquefactionDifferentiate(bgdIsLique.get() ? "1" : "0")
                                                        .specificValue(divide).liquefactionDifferentiate(bgdIsLique.get() ? "1" : "0").taskId(taskId).delFlag(YNEnum.N.toString())
                                                        .geom("POINT("+sandLiquefactionDrill.getLongitude()+" "+sandLiquefactionDrill.getLatitude()+")")
                                                        .fullboreSoilDepth(h1).fullboreSoilThickness(di).wi(wi).ei(ile).build();
                                                //saveResultDetailSandLiquefaction(resultDetailSandLiquefaction);
                                                if(sandLiquefactionDrill.getDw().compareTo(BigDecimal.ZERO)==0){
                                                    zeroSumIle = zeroSumIle.add(zeroIle);
                                                    zeroFinalList.add(resultDetailSandLiquefaction);
                                                }else{
                                                    sumIle = sumIle.add(ile);
                                                    finalList.add(resultDetailSandLiquefaction);
                                                }
                                            }
                                        }
                                    }
                                }
                                saveResultDetailSandLiquefaction(finalList, sumIle);
                                saveResultDetailSandLiquefaction(zeroFinalList, zeroSumIle);
                            }
                        });
                    }
                }else{
                    //标贯法
                    Map<String, List<SandLiquefactionDrill>> drillGroup = drillList.stream().collect(Collectors.groupingBy(SandLiquefactionDrill::getDrillCode));
                    drillGroup.forEach((k,v)->{
                            //k是钻孔编号  v是该钻孔下的标贯点
                            for (BigDecimal count1 : finalBlowCount) {
                                //地震动加速度
                                BigDecimal earthquakeAcceleration = getEarthquakeAcceleration(param.getOperands(), count1);
                                List<DzzhResultDetailSandLiquefaction> finalList = new ArrayList<>();
                                for (SandLiquefactionDrill sandLiquefactionDrill : v) {
                                    //sandLiquefactionDrill是标贯点
                                    AtomicBoolean bgdIsLique = new AtomicBoolean(false);
                                    //粘粒含量
                                    BigDecimal pc = sandLiquefactionDrill.getPc();
                                    //标贯值即实际锤击数N
                                    BigDecimal standardNumber = sandLiquefactionDrill.getRealityNum();
                                    //标贯点深度
                                    BigDecimal ds = sandLiquefactionDrill.getDs();
                                    if(modelType == 2 && (ds.compareTo(new BigDecimal(10)) >= 0 && ds.compareTo(new BigDecimal(30)) <= 0)){
                                        // 公式2区域性地震安全性评价技术规范同时地面下10m-30m深度范围内
                                        // 工作等级系数
                                        BigDecimal r = BigDecimal.valueOf(1.0);
                                        BigDecimal firstDivide = (new BigDecimal(58).multiply(earthquakeAcceleration).divide((earthquakeAcceleration.
                                                add(new BigDecimal(0.4))), 2, RoundingMode.HALF_DOWN));
                                        BigDecimal firstSubtract = new BigDecimal(1).subtract(new BigDecimal(0.02).multiply(sandLiquefactionDrill.getDw()));
                                        BigDecimal secondDivide = ds.divide(ds.add(new BigDecimal(6.2)), 2, RoundingMode.HALF_DOWN);
                                        BigDecimal addPart = new BigDecimal(0.27).add(secondDivide);
                                        BigDecimal sqrtTemp = new BigDecimal(3).divide(pc, 2, RoundingMode.HALF_DOWN);
                                        BigDecimal sqrtResult = BigDecimal.valueOf(Math.sqrt(sqrtTemp.doubleValue()));
                                        BigDecimal ncr = r.multiply(retioβ).multiply(firstDivide).multiply(firstSubtract).multiply(addPart).multiply(sqrtResult);
                                        BigDecimal divide = standardNumber.divide(ncr, 2, RoundingMode.DOWN);
                                        if (divide.compareTo(new BigDecimal(1)) <= 0) {
                                            // 大于1则该层标贯试验点为不液化，小于等于1则液化
                                            bgdIsLique.set(true);
                                        }
                                        DzzhResultDetailSandLiquefaction resultDetailSandLiquefaction =
                                                DzzhResultDetailSandLiquefaction.builder()
                                                        .drslId(UUIDGenerator.getUUID()).earthquakeAcceleration(earthquakeAcceleration).groundWaterDepth(sandLiquefactionDrill.getDw())
                                                        .longitude(sandLiquefactionDrill.getLongitude()).latitude(sandLiquefactionDrill.getLatitude())
                                                        .liquefactionGroundWaterDepth(sandLiquefactionDrill.getDw()).adjustFactor(param.getAdjustFactor()).drillCode(sandLiquefactionDrill.getDrillCode())
                                                        .stratumNum(sandLiquefactionDrill.getPointNum()).stratumDepth(sandLiquefactionDrill.getBottomDepth())
                                                        .layerThickness(sandLiquefactionDrill.getLayerThickness()).geotechnicalName(sandLiquefactionDrill.getGeotechnicalName()).clayContent(pc.toString())
                                                        .ncr(ncr).actualBlowsNumber(sandLiquefactionDrill.getRealityNum()).algorithmType(param.getAlgorithmType())
                                                        .drillLiquefactionDifferentiate( bgdIsLique.get() ? "1" : "0").specificValue(divide).ds(ds)
                                                        .liquefactionDifferentiate(bgdIsLique.get() ? "1" : "0").taskId(taskId).delFlag(YNEnum.N.toString())
                                                        .geom("POINT("+sandLiquefactionDrill.getLongitude()+" "+sandLiquefactionDrill.getLatitude()+")").ds(sandLiquefactionDrill.getDs()).dmslId(dmslId)
                                                        .build();
                                        finalList.add(resultDetailSandLiquefaction);
                                    }else{
                                        //公式1建筑抗震设计规范 或模型是区域性地震安全性评价技术规范但在地面下10m深度范围内
                                        BigDecimal lnTemp = (new BigDecimal(0.6).multiply(ds).add(new BigDecimal(1.5)));
                                        Double lnResult = Math.log(lnTemp.doubleValue());
                                        BigDecimal dwTemp = sandLiquefactionDrill.getDw().multiply(new BigDecimal(0.1));
                                        BigDecimal centerResult = new BigDecimal(lnResult).subtract(dwTemp);
                                        BigDecimal prefixResult = count1.multiply(retioβ).multiply(centerResult);
                                        BigDecimal sqrtTemp = new BigDecimal(3).divide(pc, 2, RoundingMode.DOWN);
                                        BigDecimal sqrtResult = BigDecimal.valueOf(Math.sqrt(sqrtTemp.doubleValue()));
                                        BigDecimal ncr = prefixResult.multiply(sqrtResult);
                                        BigDecimal divide = standardNumber.divide(ncr, 2, RoundingMode.HALF_DOWN);
                                        if (divide.compareTo(new BigDecimal(1)) <= 0) {
                                            //大于1则该层标贯试验点为不液化，小于等于1则液化
                                            bgdIsLique.set(true);
                                        }
                                        //非液化指数法时不保存液化判别水位深度
                                        DzzhResultDetailSandLiquefaction resultDetailSandLiquefaction
                                                = DzzhResultDetailSandLiquefaction.builder()
                                                .drslId(UUIDGenerator.getUUID()).dmslId(dmslId)
                                                .earthquakeAcceleration(earthquakeAcceleration).groundWaterDepth(sandLiquefactionDrill.getDw()).longitude(sandLiquefactionDrill.getLongitude())
                                                .latitude(sandLiquefactionDrill.getLatitude()).adjustFactor(retioβ).drillCode(sandLiquefactionDrill.getDrillCode()).liquefactionGroundWaterDepth(sandLiquefactionDrill.getDw())
                                                .stratumNum(sandLiquefactionDrill.getPointNum()).stratumDepth(sandLiquefactionDrill.getBottomDepth()).algorithmType(param.getAlgorithmType())
                                                .layerThickness(sandLiquefactionDrill.getLayerThickness()).geotechnicalName(sandLiquefactionDrill.getGeotechnicalName()).clayContent(pc.toString())
                                                .ncr(ncr).ds(ds)
                                                .actualBlowsNumber(sandLiquefactionDrill.getRealityNum()).drillLiquefactionDifferentiate( bgdIsLique.get() ? "1" : "0")
                                                .specificValue(divide).liquefactionDifferentiate(bgdIsLique.get() ? "1" : "0").taskId(taskId).delFlag(YNEnum.N.toString())
                                                .geom("POINT("+sandLiquefactionDrill.getLongitude()+" "+sandLiquefactionDrill.getLatitude()+")")
                                                .build();
                                        finalList.add(resultDetailSandLiquefaction);
                                    }
                                }
                                sandLiquefactionRepository.saveResultDetailSandLiquefaction(finalList);
                            }
                    });
                }
            }
        }
//        else {
//            //2表示使用用户上传的数据
//            List<SandLiquefactionDrill> drillList = sandLiquefactionRepository.getUploadDrillList(taskId, versionCode);
//            if (drillList != null && drillList.size() > 0) {
//                List<BigDecimal> blowCount = null;
//                if (param.getOperands().equals(String.valueOf(OperandsEnum.SANDSILT.getState()))) {
//                    blowCount = getSoilNumList();
//                } else {
//                    blowCount = getLoessNumList();
//                }
//                List<BigDecimal> finalBlowCount = blowCount;
//                //钻孔的每一个层底深度中有多少标贯点
//                Map<String, List<SandLiquefactionDrill>> depthDrillList = drillList.stream().collect(Collectors.groupingBy(entity -> {
//                    return entity.getDrillCode() + "_" + entity.getLongitude() + "_" + entity.getLatitude() + "_" + entity.getBottomDepth();
//                }));
//                //返回的map是包含d1、h1信息的以钻孔为单位的各个标贯点信息
//                Map<String, List<SandLiquefactionDrill>> map = getAllPenetrationPointByBottomDepth(depthDrillList, param.getAdjustFactor());
//                //获取相同地震动加速度和地下水位深度的钻孔信息
//                List<String> codeList = new ArrayList<>();
//                if (PlatformObjectUtils.isNotEmpty(map)) {
//                    Map<String, List<DzzhResultDetailSandLiquefaction>> circleMap = new HashMap<>();
//                        map.forEach((k, v) -> {
//                            List<DzzhResultDetailSandLiquefaction> drslList = new ArrayList<>();
//                            for (BigDecimal count : finalBlowCount) {
//                                List<DzzhResultDetailSandLiquefaction> finalList = new ArrayList<>();
//                                List<DzzhResultDetailSandLiquefaction> zeroFinalList = new ArrayList<>();
//                                //每个钻孔下的标贯点信息  k表示每个钻孔
//                                BigDecimal sumIle = BigDecimal.ZERO;
//                                BigDecimal zeroSumIle = BigDecimal.ZERO;
//                                BigDecimal ile = BigDecimal.ZERO;
//                                BigDecimal zeroIle = BigDecimal.ZERO;
//                                for (SandLiquefactionDrill sandLiquefactionDrill : v) {
//                                    //地震动加速度
//                                    BigDecimal earthquakeAcceleration = getEarthquakeAcceleration(param.getOperands(), count);
//                                    AtomicBoolean bgdIsLique = new AtomicBoolean(false);
//                                    BigDecimal pc = sandLiquefactionDrill.getPc();
//                                    //标贯值即实际锤击数N
//                                    BigDecimal standardNumber = sandLiquefactionDrill.getRealityNum();
//                                    //标贯点深度
//                                    BigDecimal ds = sandLiquefactionDrill.getDs();
//                                    //当模型选择的是建筑抗震设计规范、或选择了区域性地震安全性评价技术规范但深度在0-10范围内的，或者选择了液化指数模型（此时不区分砂土粉土和黄土）,或者选择标贯法的饱和黄土（地面下20m深度范围内）
//                                    if ((modelType!=null && modelType == 1) || (modelType!=null && modelType == 2 && ds.compareTo(new BigDecimal(10)) < 0) || "2".equals(param.getAlgorithmType()) || (modelType==null && ds.compareTo(new BigDecimal(20)) < 0)) {
//                                        //公式1建筑抗震设计规范 或模型是区域性地震安全性评价技术规范但在地面下10m深度范围内
//                                        BigDecimal lnTemp = (new BigDecimal(0.6).multiply(ds).add(new BigDecimal(1.5)));
//                                        Double lnResult = Math.log(lnTemp.doubleValue());
//                                        BigDecimal dwTemp = sandLiquefactionDrill.getDw().multiply(new BigDecimal(0.1));
//                                        BigDecimal centerResult = new BigDecimal(lnResult).subtract(dwTemp);
//                                        BigDecimal prefixResult = count.multiply(retioβ).multiply(centerResult);
//                                        BigDecimal sqrtTemp = new BigDecimal(3).divide(pc, 2, RoundingMode.DOWN);
//                                        BigDecimal sqrtResult = BigDecimal.valueOf(Math.sqrt(sqrtTemp.doubleValue()));
//                                        BigDecimal ncr = prefixResult.multiply(sqrtResult);
//                                        BigDecimal divide = standardNumber.divide(ncr, 2, RoundingMode.HALF_DOWN);
//                                        if (divide.compareTo(new BigDecimal(1)) <= 0) {
//                                            //大于1则该层标贯试验点为不液化，小于等于1则液化
//                                            bgdIsLique.set(true);
//                                        }
//                                        //液化指数法
//                                        if ("2".equals(param.getAlgorithmType())) {
//                                            //获取钻孔下的标贯点且标贯点的标贯点深度在液化判别深度内的才计算液化指数ile。
//                                            if (ds.compareTo(param.getAdjustFactor()) <= 0) {
//                                                BigDecimal divideValue = BigDecimal.valueOf(1);
//                                                //实测值除临界值的值A如果A大于等于1则比值取1，比值小于0，比如0.2，那取值0.2
//                                                if (divide.compareTo(BigDecimal.valueOf(1)) < 0) {
//                                                    divideValue = divide;
//                                                }
//                                                BigDecimal firstDivide = new BigDecimal(1).subtract(divideValue);
//                                                BigDecimal di = sandLiquefactionDrill.getD1();
//                                                BigDecimal h1 = sandLiquefactionDrill.getH1();
//                                                BigDecimal wi = BigDecimal.ZERO;
//                                                //当该层中点深度hi不大于5m时应采用10，等于20m时应采用零值，5~20m时应按线性内插法取值。
//                                                if (h1.compareTo(BigDecimal.valueOf(9999)) == 0) {
//                                                    wi = BigDecimal.ZERO;
//                                                    h1 = BigDecimal.ZERO;
//                                                } else {
//                                                    if (h1.compareTo(new BigDecimal(5)) <= 0) {
//                                                        wi = BigDecimal.valueOf(10);
//                                                    } else if (h1.compareTo(new BigDecimal(20)) == 0) {
//                                                        wi = BigDecimal.ZERO;
//                                                    } else if (h1.compareTo(new BigDecimal(5)) > 0 && h1.compareTo(new BigDecimal(20)) < 0) {
//                                                        //线性内插法求值 线性内插法公式是Y=Y1+（Y2-Y1）×（X-X1）／（X2-X1）    x处于x1和x2之间，y处于y1和y2之间
//                                                        BigDecimal fdivide = (BigDecimal.ZERO.subtract(BigDecimal.valueOf(10))).divide(new BigDecimal(20).subtract(new BigDecimal(5)), 2, RoundingMode.HALF_DOWN);
//                                                        wi = BigDecimal.valueOf(10).add(fdivide.multiply(h1.subtract(new BigDecimal(5))));
//                                                    }
//                                                }
//                                                if(sandLiquefactionDrill.getDw().compareTo(BigDecimal.ZERO)==0){
//                                                    zeroIle = firstDivide.multiply(di).multiply(wi);
//                                                }else{
//                                                    ile = firstDivide.multiply(di).multiply(wi);
//                                                }
//
//                                                String sandLevel = getSandLevel(ile);
//                                                String drslId = UUIDGenerator.getUUID();
//                                                //选择的是上传的数据，那么不保存标贯点顶深和低深
//                                                DzzhResultDetailSandLiquefaction resultDetailSandLiquefaction
//                                                        = DzzhResultDetailSandLiquefaction.builder()
//                                                        .drslId(drslId).dmslId(dmslId)
//                                                        .earthquakeAcceleration(earthquakeAcceleration).groundWaterDepth(sandLiquefactionDrill.getDw()).longitude(sandLiquefactionDrill.getLongitude())
//                                                        .latitude(sandLiquefactionDrill.getLatitude()).liquefactionGroundWaterDepth(sandLiquefactionDrill.getDw()).adjustFactor(retioβ).drillCode(sandLiquefactionDrill.getDrillCode())
//                                                        .stratumNum(sandLiquefactionDrill.getPointNum()).stratumDepth(sandLiquefactionDrill.getBottomDepth())
//                                                        .layerThickness(sandLiquefactionDrill.getLayerThickness()).geotechnicalName(sandLiquefactionDrill.getGeotechnicalName())
//                                                        .clayContent(pc.toString()).ncr(ncr).wi(wi).ei(ile).ds(ds).sandLevel(sandLevel).algorithmType(param.getAlgorithmType())
//                                                        .actualBlowsNumber(sandLiquefactionDrill.getRealityNum()).drillLiquefactionDifferentiate(bgdIsLique.get() ? "1" : "0")
//                                                        .specificValue(divide).liquefactionDifferentiate(bgdIsLique.get() ? "1" : "0").taskId(taskId).delFlag(YNEnum.N.toString())
//                                                        .geom("POINT("+sandLiquefactionDrill.getLongitude()+" "+sandLiquefactionDrill.getLatitude()+")")
//                                                        .fullboreSoilDepth(h1).fullboreSoilThickness(di).wi(wi).ei(ile).build();
//                                                //saveResultDetailSandLiquefaction(resultDetailSandLiquefaction);
//                                                if(sandLiquefactionDrill.getDw().compareTo(BigDecimal.ZERO)==0){
//                                                    zeroSumIle = zeroSumIle.add(zeroIle);
//                                                    zeroFinalList.add(resultDetailSandLiquefaction);
//                                                }else{
//                                                    sumIle = sumIle.add(ile);
//                                                    finalList.add(resultDetailSandLiquefaction);
//                                                }
//                                                //getDrillMap(drillMap, codeMap, earthquakeAcceleration, sandLiquefactionDrill.getDw(), resultDetailSandLiquefaction);
//                                            }
//                                        }
//                                        //标贯法
//                                        if (!"2".equals(param.getAlgorithmType())) {
//                                            //非液化指数法时不保存液化判别水位深度
//                                            DzzhResultDetailSandLiquefaction resultDetailSandLiquefaction
//                                                    = DzzhResultDetailSandLiquefaction.builder()
//                                                    .drslId(UUIDGenerator.getUUID()).dmslId(dmslId)
//                                                    .earthquakeAcceleration(earthquakeAcceleration).groundWaterDepth(sandLiquefactionDrill.getDw()).longitude(sandLiquefactionDrill.getLongitude())
//                                                    .latitude(sandLiquefactionDrill.getLatitude()).adjustFactor(retioβ).drillCode(sandLiquefactionDrill.getDrillCode()).liquefactionGroundWaterDepth(sandLiquefactionDrill.getDw())
//                                                    .stratumNum(sandLiquefactionDrill.getPointNum()).stratumDepth(sandLiquefactionDrill.getBottomDepth()).algorithmType(param.getAlgorithmType())
//                                                    .layerThickness(sandLiquefactionDrill.getLayerThickness()).geotechnicalName(sandLiquefactionDrill.getGeotechnicalName()).clayContent(pc.toString())
//                                                    .ncr(ncr).ds(ds)
//                                                    .actualBlowsNumber(sandLiquefactionDrill.getRealityNum()).drillLiquefactionDifferentiate( bgdIsLique.get() ? "1" : "0")
//                                                    .specificValue(divide).liquefactionDifferentiate(bgdIsLique.get() ? "1" : "0").taskId(taskId).delFlag(YNEnum.N.toString())
//                                                    .geom("POINT("+sandLiquefactionDrill.getLongitude()+" "+sandLiquefactionDrill.getLatitude()+")")
//                                                    .build();
//                                            //saveResultDetailSandLiquefaction(resultDetailSandLiquefaction);
//                                            finalList.add(resultDetailSandLiquefaction);
//                                            //获取相同地震动加速度、地下水位深度的钻孔（非标贯点数据）数据
//                                            //getDrillMap(drillMap, codeMap, earthquakeAcceleration, sandLiquefactionDrill.getDw(), resultDetailSandLiquefaction);
//                                        }
//                                    }else if(modelType == 2 && (ds.compareTo(new BigDecimal(10)) >= 0 && ds.compareTo(new BigDecimal(30)) <= 0)){
//                                        // 公式2区域性地震安全性评价技术规范同时地面下10m-30m深度范围内
//                                        // 工作等级系数
//                                        BigDecimal r = BigDecimal.valueOf(1.0);
//                                        BigDecimal firstDivide = (new BigDecimal(58).multiply(earthquakeAcceleration).divide((earthquakeAcceleration.
//                                                add(new BigDecimal(0.4))), 2, RoundingMode.HALF_DOWN));
//                                        BigDecimal firstSubtract = new BigDecimal(1).subtract(new BigDecimal(0.02).multiply(sandLiquefactionDrill.getDw()));
//                                        BigDecimal secondDivide = ds.divide(ds.add(new BigDecimal(6.2)), 2, RoundingMode.HALF_DOWN);
//                                        BigDecimal addPart = new BigDecimal(0.27).add(secondDivide);
//                                        BigDecimal sqrtTemp = new BigDecimal(3).divide(pc, 2, RoundingMode.HALF_DOWN);
//                                        BigDecimal sqrtResult = BigDecimal.valueOf(Math.sqrt(sqrtTemp.doubleValue()));
//                                        BigDecimal ncr = r.multiply(retioβ).multiply(firstDivide).multiply(firstSubtract).multiply(addPart).multiply(sqrtResult);
//                                        BigDecimal divide = standardNumber.divide(ncr, 2, RoundingMode.DOWN);
//                                        if (divide.compareTo(new BigDecimal(1)) <= 0) {
//                                            bgdIsLique.set(true);
//                                            // 大于1则该层标贯试验点为不液化，小于等于1则液化
//                                        }
//                                        DzzhResultDetailSandLiquefaction resultDetailSandLiquefaction =
//                                                DzzhResultDetailSandLiquefaction.builder()
//                                                        .drslId(UUIDGenerator.getUUID()).earthquakeAcceleration(earthquakeAcceleration).groundWaterDepth(sandLiquefactionDrill.getDw())
//                                                        .longitude(sandLiquefactionDrill.getLongitude()).latitude(sandLiquefactionDrill.getLatitude())
//                                                        .liquefactionGroundWaterDepth(sandLiquefactionDrill.getDw()).adjustFactor(param.getAdjustFactor()).drillCode(sandLiquefactionDrill.getDrillCode())
//                                                        .stratumNum(sandLiquefactionDrill.getPointNum()).stratumDepth(sandLiquefactionDrill.getBottomDepth())
//                                                        .layerThickness(sandLiquefactionDrill.getLayerThickness()).geotechnicalName(sandLiquefactionDrill.getGeotechnicalName()).clayContent(pc.toString())
//                                                        .ncr(ncr).actualBlowsNumber(sandLiquefactionDrill.getRealityNum()).algorithmType(param.getAlgorithmType())
//                                                        .drillLiquefactionDifferentiate( bgdIsLique.get() ? "1" : "0").specificValue(divide).ds(ds)
//                                                        .liquefactionDifferentiate(bgdIsLique.get() ? "1" : "0").taskId(taskId).delFlag(YNEnum.N.toString())
//                                                        .geom("POINT("+sandLiquefactionDrill.getLongitude()+" "+sandLiquefactionDrill.getLatitude()+")").ds(sandLiquefactionDrill.getDs()).dmslId(dmslId)
//                                                        .build();
//                                        finalList.add(resultDetailSandLiquefaction);
//                                        //获取相同地震动加速度、地下水位深度的钻孔（非标贯点数据）数据
//                                        //getDrillMap(drillMap, codeMap, earthquakeAcceleration, sandLiquefactionDrill.getDw(), resultDetailSandLiquefaction);
//                                    }
//
//                                }
//                                if ("2".equals(param.getAlgorithmType())) {
//                                    saveResultDetailSandLiquefaction(finalList, sumIle);
//                                    saveResultDetailSandLiquefaction(zeroFinalList, zeroSumIle);
//                                }else{
//                                    sandLiquefactionRepository.saveResultDetailSandLiquefaction(finalList);
//                                }
//                                if(finalList.size()>0){
//                                    drslList.addAll(finalList);
//                                }
//                                if(zeroFinalList.size()>0){
//                                    drslList.addAll(zeroFinalList);
//                                }
//                            }
////                            List<DzzhResultDetailSandLiquefaction> finalList = new ArrayList<>();
////                            if(PlatformObjectUtils.isNotEmpty(drslList)){
////                                Map<String, List<DzzhResultDetailSandLiquefaction>> collect = drslList.stream().collect(Collectors.groupingBy(dzzhResultDetailSandLiquefaction -> {
////                                    return dzzhResultDetailSandLiquefaction.getEarthquakeAcceleration() + "_" + dzzhResultDetailSandLiquefaction.getLiquefactionGroundWaterDepth();
////                                }));
////                                collect.forEach((k11,v11)->{
////                                    long count = v11.stream().filter(entity -> {
////                                        return "1".equals(entity.getLiquefactionDifferentiate());
////                                    }).count();
////                                    if(count>0){
////                                        v11.forEach(entity->entity.setDrillLiquefactionDifferentiate("1"));
////                                    }
////                                    finalList.addAll(v11);
////                                });
////                            }
//
//                        });
//
//                    //液化结果分布图，以钻孔点为圆心，以两口钻井间距的一半为半径的圆形判别为液化，其他区域为不液化，从而得到一个区域的液化评价结果。
//                    //getAndSaveSandCircle(drillMap, taskId);
//                }
//            }
//        }
    }

    private void getDrillMap(Map<String, List<DzzhResultDetailSandLiquefaction>> drillMap, Map<String, String> codeMap, BigDecimal earthquakeAcceleration, BigDecimal dwt, DzzhResultDetailSandLiquefaction resultDetailSandLiquefaction) {
        if (!drillMap.containsKey(earthquakeAcceleration + "_" + dwt)) {
            if (!codeMap.containsKey(earthquakeAcceleration + "_" + dwt + "_" + resultDetailSandLiquefaction.getDrillCode())) {
                codeMap.put(earthquakeAcceleration + "_" + dwt + "_" + resultDetailSandLiquefaction.getDrillCode(), "1");
                List<DzzhResultDetailSandLiquefaction> list = new ArrayList<>();
                list.add(resultDetailSandLiquefaction);
                drillMap.put(earthquakeAcceleration + "_" + dwt, list);
            }
        } else {
            if (!codeMap.containsKey(earthquakeAcceleration + "_" + dwt + "_" + resultDetailSandLiquefaction.getDrillCode())) {
                codeMap.put(earthquakeAcceleration + "_" + dwt + "_" + resultDetailSandLiquefaction.getDrillCode(), "1");
                List<DzzhResultDetailSandLiquefaction> list = drillMap.get(earthquakeAcceleration + "_" + dwt);
                list.add(resultDetailSandLiquefaction);
                drillMap.put(earthquakeAcceleration + "_" + dwt, list);
            }
        }
    }

    private void getAndSaveSandCircle(Map<String, List<DzzhResultDetailSandLiquefaction>> drillMap, String taskId) {
        List<SandCircleVO> sandCircleVOS = new ArrayList();
        if (drillMap.values().size() > 0) {
            //k是地震动加速度_地下水位深度 ,v的k是钻孔编号，v是一个钻孔对应的一个标贯点（一个钻孔有多个标贯点，也只取其中的1个标贯点
            //同属一个钻孔的标贯点的钻孔编号、经度、纬度和是否液化都一致）
            drillMap.forEach((k, v) -> {
                for (DzzhResultDetailSandLiquefaction entity : v) {
                    BigDecimal nearestDistance = BigDecimal.valueOf(-1);
                    BigDecimal nearDistance = BigDecimal.ZERO;
                    BigDecimal longitude = entity.getLongitude();
                    BigDecimal latitude = entity.getLatitude();
                    for (DzzhResultDetailSandLiquefaction domain : v) {
                        if (!entity.getDrillCode().equals(domain.getDrillCode())) {
                            BigDecimal longitude1 = domain.getLongitude();
                            BigDecimal latitude1 = domain.getLatitude();
                            nearDistance = sandLiquefactionRepository.getNearestDistanceByDrill(longitude, latitude, longitude1, latitude1);
                            if (nearestDistance.compareTo(BigDecimal.ZERO) < 0 || nearDistance.compareTo(nearestDistance) < 0) {
                                nearestDistance = nearDistance;
                            }
                        }
                    }
                    BigDecimal radius = nearestDistance.divide(BigDecimal.valueOf(2), RoundingMode.HALF_DOWN);
                    Polygon circle = createCircle(longitude.doubleValue(), latitude.doubleValue(), radius.doubleValue());
                    //钻孔液化判别
                    String drillLiquefactionDifferentiate = entity.getDrillLiquefactionDifferentiate();
                    SandCircleVO vo = new SandCircleVO();
                    vo.setTaskId(taskId).setDmslId(entity.getDmslId()).setEarthquakeAcceleration(entity.getEarthquakeAcceleration()).setDrscId(UUIDGenerator.getUUID()).
                            setLiquefactionGroundWaterDepth(entity.getLiquefactionGroundWaterDepth()).setGeom(circle.toString()).setSand(drillLiquefactionDifferentiate);
                    sandCircleVOS.add(vo);
                }
            });
        }
        //保存时直接转换成空间数据
        if (sandCircleVOS.size() > 0) {
            sandLiquefactionRepository.saveSandCircle(sandCircleVOS);
        }
    }

    private BigDecimal getEarthquakeAcceleration(String operands, BigDecimal count) {
        BigDecimal earthquakeAcceleration = BigDecimal.ZERO;
        if (operands.equals(String.valueOf(OperandsEnum.SANDSILT.getState()))) {
            if (count.compareTo(new BigDecimal(12)) == 0) {
                earthquakeAcceleration = new BigDecimal(0.20);
            } else if (count.compareTo(new BigDecimal(16)) == 0) {
                earthquakeAcceleration = new BigDecimal(0.30);
            } else if (count.compareTo(new BigDecimal(19)) == 0) {
                earthquakeAcceleration = new BigDecimal(0.40);
            }
        } else {
            if (count.compareTo(new BigDecimal(9)) == 0) {
                earthquakeAcceleration = new BigDecimal(0.20);
            } else if (count.compareTo(new BigDecimal(11)) == 0) {
                earthquakeAcceleration = new BigDecimal(0.30);
            } else if (count.compareTo(new BigDecimal(13)) == 0) {
                earthquakeAcceleration = new BigDecimal(0.40);
            }
        }
        return earthquakeAcceleration;
    }

    /**
     * 根据圆形中心点经纬度、半径生成圆形（类圆形，32边多边形）
     *
     * @param x      中心点经度
     * @param y      中心点纬度
     * @param radius 半径（米）
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Polygon createCircle(double x, double y, final double radius) {
        //将半径转换为度数
        double radiusDegree = parseYLengthToDegree(radius);
        //生成工厂类
        GeometricShapeFactory shapeFactory = new GeometricShapeFactory();
        //设置生成的类圆形边数
        shapeFactory.setNumPoints(32);
        //设置圆形中心点经纬度
        shapeFactory.setCentre(new Coordinate(x, y));
        //设置圆形直径
        shapeFactory.setSize(radiusDegree * 2);
        //使用工厂类生成圆形
        Polygon circle = shapeFactory.createCircle();
        return circle;
    }

    /**
     * 将Y轴的长度（米）转换成纬度
     *
     * @param length
     * @return
     */
    public double parseYLengthToDegree(double length) {
        //将length长度转换为度数
        double yDegree = length / P_EARTH * 360;
        return yDegree;
    }

    private String getSandLevel(BigDecimal ile) {
        if (ile.compareTo(BigDecimal.ZERO) > 0 && ile.compareTo(BigDecimal.valueOf(6)) <= 0) {
            return "轻微";
        } else if (ile.compareTo(BigDecimal.valueOf(6)) > 0 && ile.compareTo(BigDecimal.valueOf(18)) <= 0) {
            return "中等";
        } else if (ile.compareTo(BigDecimal.ZERO) == 0) {
            return "不液化";
        }
        return "严重";
    }

    //根据层底深度获取在这层底深度中的所有的标贯点并计算
    private Map<String, List<SandLiquefactionDrill>> getAllPenetrationPointByBottomDepth(Map<String, List<SandLiquefactionDrill>> depthDrillList, BigDecimal retioβ) {
        BigDecimal halfValue = BigDecimal.valueOf(2);
        //获取的是每个钻孔下的标贯点信息
        Map<String, List<SandLiquefactionDrill>> map = new HashMap<>();
        depthDrillList.forEach((k, v) -> {
            //k是一个钻孔下的多个层底深度
            //v是一个层底深度中的多个标贯点信息
            List<SandLiquefactionDrill> sandLiquefactionDrillList = new ArrayList<>();
            //当标贯点是第一个时，此时前一个标贯点的层底深度设置为0；
            BigDecimal topDepth = BigDecimal.ZERO;
            //层底深度
            BigDecimal bottomDepth = new BigDecimal(k.split("_")[3]);
            //每个层底深度有多少标贯点
            List<SandLiquefactionDrill> list = v;
            //该层底深度中的标贯点个数
            int count = list.size();

            SandLiquefactionDrill drill = list.get(0);
            //水位深度  同一个钻孔的水位深度相同
            BigDecimal dw1 = drill.getDw();
            List<BigDecimal> dwList = new ArrayList<>();
            dwList.add(dw1);
            if (dw1.compareTo(BigDecimal.ZERO) > 0) {
                //如果水位深度大于0，则计算0和具体的值，否则只计算0
                dwList.add(BigDecimal.ZERO);
            }
            //当该层底深度中只有一个标贯点
            if (count == 1) {
                //当水位深度大于0时需要计算dw分别等于0和具体值的结果
                for (BigDecimal dw : dwList) {
                    SandLiquefactionDrill sandLiquefactionDrill = new SandLiquefactionDrill();
                    BeanUtils.copyProperties(drill, sandLiquefactionDrill);
                    BigDecimal d1 = BigDecimal.ZERO;
                    BigDecimal h1 = BigDecimal.ZERO;
                    sandLiquefactionDrill.setDw(dw);
                    //1、当地下水位dw＜层底深度Zi时
                    if (dw.compareTo(bottomDepth) < 0) {
                        //Zi(底层深度)取值不超过液化判别深度retioβ时d1=Zi-Zi-1否则d1=retioβ-Zi-1
                        if (bottomDepth.compareTo(retioβ) > 0) {
                            d1 = retioβ.subtract(drill.getBottomDepth());
                        } else {
                            d1 = bottomDepth.subtract(topDepth);
                        }
                        sandLiquefactionDrill.setD1(d1);
                        //hi中点=Zi-1+d1/2
                        h1 = topDepth.add(d1.divide(halfValue, 2, BigDecimal.ROUND_HALF_DOWN));
                        sandLiquefactionDrill.setH1(h1);
                    } else {
                        //2、如dw＞Z1（第一层在地下水位之上，不需要计算液化指数，di=0）
                        sandLiquefactionDrill.setD1(BigDecimal.ZERO);
                        sandLiquefactionDrill.setH1(BigDecimal.valueOf(9999));
                    }
                    sandLiquefactionDrillList.add(sandLiquefactionDrill);
                }
            } else {
                //大于等于2个标贯点
                for (int j = 0; j < list.size(); j++) {
                    BigDecimal d1 = BigDecimal.ZERO;
                    for (BigDecimal dw : dwList) {
                        SandLiquefactionDrill currentSandLiquefactionDrill = new SandLiquefactionDrill();
                        //第一个标贯点
                        if (j == 0) {
                            drill = list.get(j);
                            BeanUtils.copyProperties(drill, currentSandLiquefactionDrill);
                            currentSandLiquefactionDrill.setDw(dw);
                            SandLiquefactionDrill drillNext = list.get(j + 1);
                            BigDecimal hj = drill.getDs();
                            BigDecimal hj1 = drillNext.getDs();
                            BigDecimal centerResult = (hj1.add(hj)).divide(halfValue, 2, RoundingMode.HALF_DOWN);
                            //1、当dw＜Z1时，d1=(hi+1+hi)/2-Zi-1且(hi+1+hi)/2取值不超过液化判别深度（界面输入的值），hi中点=Zi-1+d1/2
                            if (dw.compareTo(bottomDepth) < 0) {
                                //d1=(hi+1+hi)/2-Zi-1且(hi+1+hi)/2取值不超过液化判别深度retioβ，否则 d1=retioβ-Zi-1
                                if (centerResult.compareTo(retioβ) > 0) {
                                    d1 = retioβ.subtract(topDepth);
                                } else {
                                    d1 = centerResult.subtract(topDepth);
                                }
                                currentSandLiquefactionDrill.setD1(d1);
                                BigDecimal h1 = topDepth.add(d1.divide(halfValue, 2, RoundingMode.HALF_DOWN));
                                currentSandLiquefactionDrill.setH1(h1);
                            } else {
                                //2、当Zn＞dw＞Z1时，，di=(hi+1+hi)/2-dw且(hi+1+hi)/2取值不超过液化判别深度（界面输入的值），hi中点=dw+d1/2，
                                // 如dw＞Z1（第一层在地下水位之上，不需要计算液化指数，di=0）
                                //2、如dw＞Z1（第一层在地下水位之上，不需要计算液化指数，di=0）
                                currentSandLiquefactionDrill.setD1(BigDecimal.ZERO);
                                currentSandLiquefactionDrill.setH1(BigDecimal.valueOf(9999));
                            }
                        } else if (j < list.size() - 1) {
                            drill = list.get(j);
                            BeanUtils.copyProperties(drill, currentSandLiquefactionDrill);
                            currentSandLiquefactionDrill.setDw(dw);
                            BigDecimal hi = drill.getDs();
                            SandLiquefactionDrill drillNext = list.get(j + 1);
                            BigDecimal hi1 = drillNext.getDs();
                            SandLiquefactionDrill prefixDrill = list.get(j - 1);
                            BigDecimal hi0 = prefixDrill.getDs();
                            BigDecimal centerResult = (hi1.add(hi)).divide(halfValue, 2, RoundingMode.HALF_DOWN);
                            if (centerResult.compareTo(BigDecimal.valueOf(15)) > 0) {
                                centerResult = BigDecimal.valueOf(15);
                            }
                            if (centerResult.compareTo(retioβ) > 0) {
                                //当(hi+1+hi)/2>液化判别深度，di=液化判别深度-(hi-1+hi)
                                d1 = retioβ.subtract(hi0.add(hi));
                            } else {
                                //当(hi+1+hi)/2≤液化判别深度，di=(hi+1-hi-1)/2
                                d1 = (hi1.subtract(hi0)).divide(halfValue, 2, RoundingMode.HALF_DOWN);
                            }
                            //hi中点=(hi+hi-1)/2+di/2
                            BigDecimal h1 = (hi.add(hi0)).divide(halfValue, 2, RoundingMode.HALF_DOWN).add(d1.divide(halfValue, 2, RoundingMode.HALF_DOWN));
                            currentSandLiquefactionDrill.setD1(d1);
                            currentSandLiquefactionDrill.setH1(h1);
                        } else if (j == list.size() - 1) {
                            //表示是该层的最后一个标贯点
                            drill = list.get(j);
                            BigDecimal hn = drill.getDs();
                            BeanUtils.copyProperties(drill, currentSandLiquefactionDrill);
                            currentSandLiquefactionDrill.setDw(dw);
                            if (hn.compareTo(retioβ) > 0) {
                                //当hn>液化判别深度，则di=0，hi中点不需计算
                                currentSandLiquefactionDrill.setD1(BigDecimal.valueOf(0));
                                currentSandLiquefactionDrill.setH1(BigDecimal.valueOf(9999));
                            } else {
                                //当hn≤液化判别深度，dn=Zi-(hn-1+hn)/2，hi中点=(hn+hn-1)/2+dn/2
                                SandLiquefactionDrill prefixDrill = list.get(j - 1);
                                BigDecimal prefixHn = prefixDrill.getDs();
                                BigDecimal centerResult = prefixHn.add(hn);
                                d1 = bottomDepth.subtract(centerResult.divide(halfValue, 2, RoundingMode.HALF_DOWN));
                                BigDecimal h1 = centerResult.divide(halfValue, 2, RoundingMode.HALF_DOWN).add(d1.divide(halfValue, 2, RoundingMode.HALF_DOWN));
                                currentSandLiquefactionDrill.setD1(d1);
                                currentSandLiquefactionDrill.setH1(h1);
                            }
                        }
                        sandLiquefactionDrillList.add(currentSandLiquefactionDrill);
                    }
                }
            }
            String key = (k.split("_")[0] + "_" + k.split("_")[1] + "_" + k.split("_")[2]);
            if (map.containsKey(key)) {
                List<SandLiquefactionDrill> drills = map.get(key);
                drills.addAll(sandLiquefactionDrillList);
                map.put(key, drills);
            } else {
                map.put(key, sandLiquefactionDrillList);
            }
        });
        return map;
    }

    //根据层底深度获取在这层底深度中的所有的标贯点
    private List<JSONObject> getAllPenetrationPointByBottomDepth(BigDecimal bottomDepth, List y05List, BigDecimal topDepth, BigDecimal dw, BigDecimal retioβ) {
        BigDecimal halfValue = BigDecimal.valueOf(2);
        List<JSONObject> jsonObject05List = new ArrayList<>();
        y05List.forEach(json05 -> {
            JSONObject jsonObject05 = (JSONObject) json05;
            //标贯点顶深
            BigDecimal standardStartDepth = new BigDecimal(jsonObject05.get("standard_start_depth").toString());
            //标贯点底深
            BigDecimal standardEndDepth = new BigDecimal(jsonObject05.get("standard_end_depth").toString());
            if (standardStartDepth.compareTo(topDepth) >= 0 && standardEndDepth.compareTo(bottomDepth) < 0) {
                jsonObject05.put("dw", dw);
                jsonObject05List.add(jsonObject05);
            }
        });
        int count = jsonObject05List.size();
        //地下水位和底层深度比较
        int i = dw.compareTo(bottomDepth);
        //这个层底深度范围内只有一个标贯点
        if (count == 1) {
            JSONObject jsonObject = jsonObject05List.get(0);
            BigDecimal d1 = BigDecimal.ZERO;
            BigDecimal h1 = BigDecimal.ZERO;
            //1、当地下水位dw＜层底深度Zi时
            if (i < 0) {
                //Zi(底层深度)取值不超过液化判别深度retioβ时d1=Zi-Zi-1否则d1=retioβ-Zi-1
                if (bottomDepth.compareTo(retioβ) > 0) {
                    d1 = retioβ.subtract(topDepth);
                } else {
                    d1 = bottomDepth.subtract(topDepth);
                }
                //hi中点=Zi-1+d1/2
                h1 = topDepth.add(d1.divide(halfValue, 2, BigDecimal.ROUND_HALF_DOWN));
                jsonObject.put("h1", h1);
            } else {
                //2、当Zn＞dw＞Zi时，，d1=Zi-dw且Zi取值不超过液化判别深度（界面输入的值），hi中点=dw+d1/2
//                if(bottomDepth.compareTo(retioβ)<=0){
//                    h1 = dw.add(d1.divide(halfValue,2,RoundingMode.HALF_DOWN));
//                    jsonObject.put("h1",h1);
//                }
                jsonObject.put("d1", BigDecimal.valueOf(0));
                jsonObject.put("h1", BigDecimal.valueOf(9999));
            }

        } else {
            //多个
            //先求第一个标贯点
            for (int j = 0; j < jsonObject05List.size(); j++) {
                BigDecimal d1 = BigDecimal.valueOf(0);
                //某层存在多个标贯点，当是第一个标贯点时
                if (j == 0) {
                    JSONObject jsonObject = jsonObject05List.get(j);
                    JSONObject tempJson = jsonObject05List.get(j + 1);
                    BigDecimal hj = BigDecimal.valueOf(jsonObject.getDoubleValue("standard_end_depth"));
                    BigDecimal hj1 = BigDecimal.valueOf(tempJson.getDoubleValue("standard_end_depth"));
                    BigDecimal centerResult = (hj1.add(hj)).divide(halfValue, 2, RoundingMode.HALF_DOWN);
                    if (centerResult.compareTo(BigDecimal.valueOf(15)) > 0) {
                        centerResult = BigDecimal.valueOf(15);
                    }
                    //1、当dw＜Z1时，d1=(hi+1+hi)/2-Zi-1且(hi+1+hi)/2取值不超过液化判别深度（界面输入的值），hi中点=Zi-1+d1/2
                    if (i < 0) {
                        //d1=(hi+1+hi)/2-Zi-1且(hi+1+hi)/2取值不超过液化判别深度retioβ，否则 d1=retioβ-Zi-1
                        if (centerResult.compareTo(retioβ) > 0) {
                            d1 = retioβ.subtract(topDepth);
                        } else {
                            d1 = centerResult.subtract(topDepth);
                        }
                        jsonObject.put("d1", d1);
                        BigDecimal h1 = topDepth.add(d1.divide(halfValue, 2, RoundingMode.HALF_DOWN));
                        jsonObject.put("h1", h1);
                    } else {
                        //2、当Zn＞dw＞Z1时，，di=(hi+1+hi)/2-dw且(hi+1+hi)/2取值不超过液化判别深度（界面输入的值），hi中点=dw+d1/2，
                        // 如dw＞Z1（第一层在地下水位之上，不需要计算液化指数，di=0）
//                        if(centerResult.compareTo(retioβ)>0){
//                            d1 = retioβ.subtract(dw);
//                        }else{
//                            d1 = centerResult.subtract(dw);
//                        }
//                        jsonObject.put("d1",d1);
//                        if(centerResult.compareTo(retioβ)<=0){
//                            BigDecimal h1 = dw.add(d1.divide(halfValue,2,RoundingMode.HALF_DOWN));
//                            jsonObject.put("h1",h1);
//                        }
                        jsonObject.put("d1", BigDecimal.valueOf(0));
                        jsonObject.put("h1", BigDecimal.valueOf(9999));
                    }
                } else if (j < jsonObject05List.size() - 1) {
                    JSONObject jsonObject = jsonObject05List.get(j);
                    BigDecimal hi = BigDecimal.valueOf(jsonObject.getDoubleValue("standard_end_depth"));
                    JSONObject nextJson = jsonObject05List.get(j + 1);
                    BigDecimal hi1 = BigDecimal.valueOf(nextJson.getDoubleValue("standard_end_depth"));
                    JSONObject prefixJson = jsonObject05List.get(j - 1);
                    BigDecimal hi0 = BigDecimal.valueOf(prefixJson.getDoubleValue("standard_end_depth"));
                    BigDecimal centerResult = (hi1.add(hi)).divide(halfValue, 2, RoundingMode.HALF_DOWN);
                    if (centerResult.compareTo(retioβ) > 0) {
                        //当(hi+1+hi)/2>液化判别深度，di=液化判别深度-(hi-1+hi)
                        d1 = retioβ.subtract(hi0.add(hi));
                    } else {
                        //当(hi+1+hi)/2≤液化判别深度，di=(hi+1-hi-1)/2
                        d1 = (hi1.subtract(hi0)).divide(halfValue, 2, RoundingMode.HALF_DOWN);
                    }
                    //hi中点=(hi+hi-1)/2+di/2
                    BigDecimal h1 = (hi.add(hi0)).divide(halfValue, 2, RoundingMode.HALF_DOWN).add(d1.divide(halfValue, 2, RoundingMode.HALF_DOWN));
                    jsonObject.put("d1", d1);
                    jsonObject.put("h1", h1);
                } else if (j == jsonObject05List.size() - 1) {
                    //表示是该层的最后一个标贯点
                    JSONObject jsonObject = jsonObject05List.get(j);
                    BigDecimal hn = BigDecimal.valueOf(jsonObject.getDoubleValue("standard_end_depth"));
                    if (hn.compareTo(retioβ) > 0) {
                        //当hn>液化判别深度，则di=0，hi中点不需计算
                        d1 = BigDecimal.valueOf(0);
                        jsonObject.put("d1", d1);
                        jsonObject.put("h1", BigDecimal.valueOf(9999));
                    } else {
                        //当hn≤液化判别深度，dn=Zi-(hn-1+hn)/2，hi中点=(hn+hn-1)/2+dn/2
                        JSONObject prefixJson = jsonObject05List.get(j - 1);
                        BigDecimal prefixHn = BigDecimal.valueOf(prefixJson.getDoubleValue("standard_end_depth"));
                        BigDecimal centerResult = prefixHn.add(hn);
                        d1 = bottomDepth.subtract(centerResult.divide(halfValue, 2, RoundingMode.HALF_DOWN));
                        BigDecimal h1 = centerResult.divide(halfValue, 2, RoundingMode.HALF_DOWN).add(d1.divide(halfValue, 2, RoundingMode.HALF_DOWN));
                        jsonObject.put("d1", d1);
                        jsonObject.put("h1", h1);
                    }
                }
            }
        }
        return jsonObject05List;
    }

    private List<BigDecimal> getLoessNumList() {
        //液化判别标准贯入锤击数基准值	9	11	13
        List<BigDecimal> countList = new ArrayList<>();
        countList.add(new BigDecimal(9));
        countList.add(new BigDecimal(11));
        countList.add(new BigDecimal(13));
        return countList;
    }

    //根据标贯点深度，锁定Y04中的数据
    private JSONObject getJcRfcpY04Data(List y04List, BigDecimal ds) {
        if (PlatformObjectUtils.isNotEmpty(y04List)) {
            BigDecimal small = BigDecimal.ZERO;
            for (Object json04 : y04List) {
                JSONObject json = (JSONObject) json04;
                if (ds.compareTo(small) >= 0 && ds.compareTo(new BigDecimal((Double) json.get("bottom_depth"))) < 0) {
                    return json;
                } else {
                    small = new BigDecimal((String) json.get("bottom_depth"));
                }
            }
        }
        return null;
    }

    private void saveResultDetailSandLiquefaction(List<DzzhResultDetailSandLiquefaction> drslList, BigDecimal sumIle) {
        if (PlatformObjectUtils.isNotEmpty(drslList) && PlatformObjectUtils.isNotEmpty(sumIle)) {
            String sandLevel = "";
            if(sumIle.compareTo(BigDecimal.ZERO)==0){
                sandLevel = "不液化";
            }else if(sumIle.compareTo(BigDecimal.ZERO)>0 && sumIle.compareTo(BigDecimal.valueOf(6))<=0){
                sandLevel = "轻微";
            }if(sumIle.compareTo(BigDecimal.valueOf(6))>0 && sumIle.compareTo(BigDecimal.valueOf(18))<=0){
                sandLevel = "中等";
            }if(sumIle.compareTo(BigDecimal.valueOf(18))>0){
                sandLevel = "严重";
            }
            String finalSandLevel = sandLevel;
            drslList.forEach(entity -> {
                entity.setDei(sumIle);
                entity.setSandLevel(finalSandLevel);
            });
        }
        sandLiquefactionRepository.saveResultDetailSandLiquefaction(drslList);
    }

    private BigDecimal getPc(String taskId, String versionCode,String id) {
        List y10List = redisTemplate.opsForList().range(RedisKeyConstants.SYSTEMPREFIX + ":drill" + ":" + taskId + ":" + versionCode+ ":" + id+ ":10", 0, -1);
        //黏粒含量ρc
        BigDecimal pc = BigDecimal.ZERO;
        if (PlatformObjectUtils.isNotEmpty(y10List)) {
            BigDecimal total = BigDecimal.ZERO;
            for (Object y10json : y10List) {
                JSONObject jsonObject = (JSONObject) y10json;
                //液化判别地下水位深度(稳定水位深度)
                BigDecimal particleCosmid005 = BigDecimal.valueOf((Double) jsonObject.get("particle_cosmid005"));
                total = total.add(particleCosmid005);
            }
            ;
            pc = total.divide(new BigDecimal(y10List.size()), 2, RoundingMode.HALF_DOWN);
        }
        if (pc.compareTo(new BigDecimal(3)) < 0) {
            pc = BigDecimal.valueOf(3);
        }
        return pc;
    }

    private List<BigDecimal> getSoilNumList() {
        //设计基本地震加速度（g）	0.20	0.30	0.40
        //液化判别标准贯入锤击数基准值	12	16	19
        List<BigDecimal> countList = new ArrayList<>();
        countList.add(new BigDecimal(12));
        countList.add(new BigDecimal(16));
        countList.add(new BigDecimal(19));
        return countList;
    }

    private List<BigDecimal> getAcceleratedSpeed() {
        List<BigDecimal> speedList = new ArrayList<>();
        speedList.add(new BigDecimal(0.2));
        speedList.add(new BigDecimal(0.3));
        speedList.add(new BigDecimal(0.4));
        return speedList;
    }

    private BigDecimal getRetioβByEarthquakeGroup(Integer earthquakeGroup) {
        BigDecimal retioβ = BigDecimal.ZERO;
        if (earthquakeGroup.equals(1)) {
            //设计地震分组 第一组
            retioβ = BigDecimal.valueOf(0.8);
        } else if (earthquakeGroup.equals(2)) {
            //设计地震分组 第一组
            retioβ = BigDecimal.valueOf(0.95);
        }
        if (earthquakeGroup.equals(3)) {
            //设计地震分组 第一组
            retioβ = BigDecimal.valueOf(1.05);
        }
        return retioβ;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse importDrillData(String taskId, String versionCode, MultipartFile file, HttpServletResponse response) throws Exception {
        if (StringUtils.isBlank(versionCode) || "0".equals(versionCode) || "undefined".equals(versionCode)) {
            versionCode = IdUtil.getSnowflakeNextIdStr();
        } else {
            sandLiquefactionRepository.delete(taskId, versionCode);
        }
        // 导入的参数信息
        ImportParams params = new ImportParams();
        // 设置简析的第一行
        params.setHeadRows(5);
        // 是否需要校验
        params.setNeedVerify(false);
        String fileName = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        //验证文件名是否合格
        if (!this.validateExcel(fileName)) {
            throw new RuntimeException("文件不是excel格式");
        }
        //根据文件名判断文件是2003版本还是2007版本
        boolean isExcel2003 = true;
        if (this.judeExcelVesrion(fileName) == 2007) {
            isExcel2003 = false;
        }
        // 获取excel内容
        Workbook wb = this.getExcelInfo(inputStream, isExcel2003);
        // 读取标题信息 其中也设置了有效列数量
        //List<Map<String,Object>> list = ExcelUtil.readExcelTitle(wb, 2, 5);
        Integer[] numArray = {5, 0, 1, 2};
        TaskEntity taskEntity = taskRepository.viewTask(taskId);
        String geom = taskEntity.getGeom();
        Map<String,Object> resultMap = readExcelValue(wb, 5,geom);
        if(StringUtils.isNotBlank(resultMap.get("msg").toString())){
            String msg = ("导入失败,"+resultMap.get("msg").toString());
            return ResponseCreator.createFailResponse(msg);
        }
        List<List<String>> dataList = (List<List<String>>) resultMap.get("valueList");
        if (PlatformObjectUtils.isNotEmpty(dataList)) {
            for (List<String> drills : dataList) {
                if(drills.size()==12){
                    sandLiquefactionRepository.importDrillData(drills, taskId, versionCode);
                }
            }
        }
        return ResponseCreator.createSuccessResponse(versionCode,"导入钻孔数据成功");
    }

    public Integer judeExcelVesrion(String filePath) {
        if (filePath.matches("^.+\\.(?i)(xls)$")) {
            //是2003的excel
            return 2003;
        } else {
            //"^.+\\.(?i)(xlsx)$"
            return 2007;
        }
    }

    /**
     * 验证EXCEL文件
     *
     * @param filePath
     * @return
     */
    private boolean validateExcel(String filePath) {
        if (filePath == null || (judeExcelVesrion(filePath) != 2003 && judeExcelVesrion(filePath) != 2007)) {
            return false;
        }
        return true;
    }

    /**
     * 根据excel里面的内容
     *
     * @param is          输入流
     * @param isExcel2003 excel是2003还是2007版本
     * @return
     */
    private Workbook getExcelInfo(InputStream is, boolean isExcel2003) {
        /** 根据版本选择创建Workbook的方式 */
        Workbook wb = null;
        try {
            // 当excel是2003时
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else { // 当excel是2007时
                wb = new XSSFWorkbook(is);
            }
            return wb;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

    /**
     * 读取Excel表头
     * titalRow标题行
     * dataRow 真实数据所在行
     *
     * @param wb
     * @return
     */
    private List<Map<String, Object>> readExcelTitle(Workbook wb, int titalRow, int dataRow) {
        //总列数
        int totalCells = 0;
        //得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        //得到Excel的行数
        int totalRows = sheet.getPhysicalNumberOfRows();
        //得到Excel的列数(前提是有行数)
        if (totalRows >= dataRow && sheet.getRow(titalRow) != null) {
            totalCells = sheet.getRow(titalRow).getPhysicalNumberOfCells();
        }
        List<Map<String, Object>> titleList = new ArrayList<Map<String, Object>>(totalCells);
        // 读取标题
        Row row = sheet.getRow(titalRow);
        if (row == null) {
            return null;
        }

        //循环Excel的列
        for (int c = 0; c < totalCells; c++) {
            Map<String, Object> temp = new HashMap<String, Object>(1);
            Cell cell = row.getCell(c);
            if (null != cell) {
                temp.put("name", getCellValue(cell));
                titleList.add(temp);
            } else {
                // 0816  遇到一个空白标题 结束
                totalCells = c;
                break;
            }
        }
        return titleList;
    }

    private String getCellValue(Cell cell) {
        String value = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        switch (cell.getCellTypeEnum()) {
            case STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case NUMERIC:
                if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                    // 数据格式
                    DecimalFormat df = new DecimalFormat("#.########");
                    value = df.format(cell.getNumericCellValue()) + "";
                } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                    value = sdf.format(cell.getDateCellValue()) + "";
                } else {
                    // 针对十位数以上的数字出现科学记数法的处理 20180820  yunguang modified
                    value = new DecimalFormat("#").format(cell.getNumericCellValue());
                }
                break;
            case BOOLEAN:
                value = cell.getBooleanCellValue() + "";
                break;
            case BLANK:
                value = "";
                break;
            default:
                value = cell.toString();
                break;
        }
        return value;
    }

    /**
     * 读取Excel内容
     * dataRow数据所在行
     *
     * @param wb
     * @return
     */
    private Map<String,Object> readExcelValue(Workbook wb, int dataRow,String geom) throws Exception {
        StringBuilder sb = new StringBuilder();
        //得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        //得到Excel的行数
        int totalRows = sheet.getPhysicalNumberOfRows();
        List<List<String>> valueList = new ArrayList();
        int r = dataRow;
        int totalCells = sheet.getRow(r).getPhysicalNumberOfCells();
        //存在合并单元格，记录合并单元格的数据
        String ceil0Str = "";
        String ceil1Str = "";
        String ceil2Str = "";
        //循环Excel行数,从第6行开始。标题不入库
        List<String> threeList = new ArrayList<>(3);
        for (; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                break;
            }
            List<String> temp = new ArrayList();
            int blackCeil = 0;
            //循环Excel的列
            for (int c = 0; c < totalCells; c++) {
                Cell cell = row.getCell(c);
                if (null != cell) {
                    String cellValue = getCellValue(cell);
                    if ("".equals(cellValue)) {
                        if ((c < 3 && r == dataRow)) {
                            throw new RuntimeException("带星号的必填项不能为空");
                        }
                        if (c < 3) {
                            temp.add(threeList.get(c));
                        } else {
                            temp.add("");
                        }
                        blackCeil++;
                    } else {
                        if (c < 3) {
                            if (PlatformObjectUtils.isNotEmpty(threeList) && threeList.size() == 3) {
                                threeList = new ArrayList<>();
                            }
                            threeList.add(cellValue);
                        }
                        temp.add(cellValue);
                    }
                }
            }
            if (blackCeil > 3 && blackCeil < (totalCells)) {
                throw new RuntimeException("带星号的必填项不能为空");
            }
            if (blackCeil == totalCells) {
                break;
            }
            if(temp.size()<12){
                continue;
            }
            BigDecimal longitude = BigDecimal.ZERO;
            BigDecimal latitude = BigDecimal.ZERO;
            try{
                longitude = new BigDecimal(temp.get(1));
                latitude=  new BigDecimal(temp.get(2));
            }catch (Exception e){
                e.printStackTrace();
            }

            //判断经纬度是否在任务区域范围内
            Boolean stIntersects = lawAnalysisRepository.getSTIntersects(geom, longitude, latitude);
            if(!stIntersects){
                sb.append("第").append(r+1).append("行钻孔不在任务范围内。");
            }else{
                valueList.add(temp);
            }
        }
        Map<String,Object> map = new HashMap(2);
        map.put("valueList",valueList);
        map.put("msg",sb.length()>0?sb.toString():"");
        return map;
    }


    @Override
    public void test() throws IllegalAccessException {
        //        Person person = new Person();
        //        String darId = UUIDGenerator.getUUID();
        //        Field[] fields = person.getClass().getDeclaredFields();
        //        if(PlatformObjectUtils.isNotEmpty(fields)){
        //            JSONObject json = new JSONObject();
        //            for(Field field:fields){
        //                field.setAccessible(true);
        //                AddData annotation = field.getAnnotation(AddData.class);
        //                if(annotation==null){
        //                    continue;
        //                }
        //                String name = field.getName();
        //                Object value = field.get(person);
        //                json.put(name,value);
        //            }
        //            if(json.size()>0){
        //                String ratio = json.toJSONString();
        //                //保存系数信息
        //                sandLiquefactionRepository.saveRatio(darId,"123","456",ratio);
        //            }
        //        }
        //        Person person = sandLiquefactionRepository.get();
        //        String ratio = person.getRatio();
        //        JSONObject parse =(JSONObject) JSONObject.parse(ratio);
        //        BigDecimal num = parse.getBigDecimal("num");
        //        System.out.println(num);
        CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println("线程1开始");
                Thread.sleep(15000);
                System.out.println("线程1结束");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 1;
        }, executor);
        CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println("线程2开始");
                Thread.sleep(8000);
                System.out.println("线程2结束");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 2;
        }, executor);
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(completableFuture2, completableFuture1);

        try {
            voidCompletableFuture.get();
            System.out.println(completableFuture2.get());
            System.out.println(completableFuture1.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("3");
    }


    @Override
    public List<DzzhResultDetailSandLiquefaction> details(String dmslId, BigDecimal earthquakeAcceleration, String liquefactionGroundWaterDepth) {
        List<DzzhResultDetailSandLiquefaction> details = sandLiquefactionRepository.details(dmslId, earthquakeAcceleration, liquefactionGroundWaterDepth);
        Map<String, List<DzzhResultDetailSandLiquefaction>> collect = details.stream().collect(Collectors.groupingBy(DzzhResultDetailSandLiquefaction::getDrillCode));
        List<DzzhResultDetailSandLiquefaction> newList = new ArrayList<>(details.size());
        collect.forEach((k,v)->{
            int size = v.size();
            v.forEach(entity->{
                if(PlatformObjectUtils.isNotEmpty(entity.getLiquefactionDifferentiate())){
                    entity.setLiquefactionDifferentiate("1".equals(entity.getLiquefactionDifferentiate())?"液化":"不液化");
                }
                if(PlatformObjectUtils.isNotEmpty(entity.getDrillLiquefactionDifferentiate())){
                    entity.setDrillLiquefactionDifferentiate("1".equals(entity.getDrillLiquefactionDifferentiate())?"液化":"不液化");
                }
                entity.setNum(size);
                newList.add(entity);
            });
        });
//        if(PlatformObjectUtils.isNotEmpty(details)){
//            details.forEach(entity->{
//                if(PlatformObjectUtils.isNotEmpty(entity.getLiquefactionDifferentiate())){
//                    entity.setLiquefactionDifferentiate("1".equals(entity.getLiquefactionDifferentiate())?"液化":"不液化");
//                }
//                if(PlatformObjectUtils.isNotEmpty(entity.getDrillLiquefactionDifferentiate())){
//                    entity.setDrillLiquefactionDifferentiate("1".equals(entity.getDrillLiquefactionDifferentiate())?"液化":"不液化");
//                }
//            });
//        }
        return newList;
    }


    @Override
    public Map<String, Object> getCenterDataPage(String taskId, int curPage, int pageSize) {
        return sandLiquefactionRepository.getCenterDataPage(taskId, curPage, pageSize);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeModel(String dmslId, String taskId, String flag) {
        //表示要将最终结果变更为中间结果
        if ("1".equals(flag)) {
            //从未参与过评估不变更
            if (!"".equals(dmslId)) {
                sandLiquefactionRepository.updateFinalModel(dmslId, taskId, ResultEnum.FINA.getState(), flag);
            }
        } else {
            //不替换就删除
            sandLiquefactionRepository.updateFinalModel(dmslId, taskId, ResultEnum.FINA.getState(), flag);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePolygonEvaluateResult(List<SandPolygonEvaluateResultVO> voList) {
        SandPolygonEvaluateResultVO sandPolygonEvaluateResultVO = voList.get(0);
        String dmslId = sandPolygonEvaluateResultVO.getDmslId();
        DzzhModelSandLiquefaction byDmslId = sandLiquefactionRepository.getByDmslId(dmslId);
        voList.forEach(entity->{
            entity.setDslperId(UUIDGenerator.getUUID());
            entity.setTaskId(byDmslId.getTaskId());
        });
        sandLiquefactionRepository.batchSavePolygonEvaluateResult(voList);
    }
    //裁剪高程数据
    private String cut(String layerName,String taskId) throws Exception{
        TaskEntity taskEntity = taskService.viewTask(taskId);
        Map<String, Object> map = new HashMap<>();
        map.put("type", "clipTif2");//只裁剪栅格
        map.put("layerName", layerName);
//        String resultLayerName1 = "高程_裁剪_" + System.currentTimeMillis();//裁剪结果数据集
        String resultLayerName1 = "temp_裁剪_" + System.currentTimeMillis();//裁剪结果数据集
        map.put("resultLayerName", resultLayerName1);
        map.put("geomText", taskEntity.getGeom());
        map.put("sourceType", "jcsjTifFile");
        RestResponse serverToken = hypergraphService.getServerToken(map);
        if (serverToken.getCode() != 200) {
            return "评估失败,裁剪高程数据失败";
        }
        return resultLayerName1;
    }
    //裁剪高程文件
    private String cutGcFile(String gcFileName,String teraVersion,String taskId) throws Exception {
        String cutedGcFileName = "";
        if(StringUtils.isBlank(gcFileName)){
            //根据高程版本获取高程文件
            gcFileName = getGcFileByVersion(teraVersion);
            //对高程数据进行裁剪
            if(StringUtils.isNotBlank(gcFileName)){
                cutedGcFileName = cut(gcFileName, taskId);
            }
        }else{
            cutedGcFileName = gcFileName;
        }
        return cutedGcFileName;
    }
    //获取综合地形指数的tif文件
    private String getComprehensiveTerrainFile(String cutedGcFileName) throws Exception {
        String topographicIndexFileName = getElevation(cutedGcFileName);
        int index = topographicIndexFileName.lastIndexOf("/");
        topographicIndexFileName =  topographicIndexFileName.replace(".tif", "");
        topographicIndexFileName = topographicIndexFileName.substring(index+1,topographicIndexFileName.length()-1);
        return topographicIndexFileName;
    }
    @Override
    public void calculateOmprehensiveTerrainIndex(String teraVersion, String taskId,Map<String,Object> map,String gcFileName,String dmslId) throws Exception {
        //获取裁剪后的高程文件
        String cutedGcFileName = cutGcFile(gcFileName,teraVersion,taskId);
        if("评估失败,裁剪高程数据失败".equals(cutedGcFileName)){
            throw new RuntimeException(cutedGcFileName);
        }
        map.put("gcFileName",cutedGcFileName);
        if (StringUtils.isBlank(dmslId)){
            dmslId = UUIDGenerator.getUUID();
        }
        //根据高程文件获取综合地形指数栅格数据
        //E:/MapData/tif/tif/gc123.tif
        if(StringUtils.isNotBlank(cutedGcFileName)){
            //获取生成的综合地形指数文件
            String topographicIndexFileName = getComprehensiveTerrainFile(cutedGcFileName);
            if(StringUtils.isNotBlank(topographicIndexFileName)){
                saveIndexFile(taskId,topographicIndexFileName,"",cutedGcFileName,dmslId);
            }
            map.put("fileName",topographicIndexFileName);
        }else{
            map.put("fileName","");
        }
        //保存信息
        saveOrUpdateModelData(taskId,teraVersion,dmslId);
        map.put("dmslId",dmslId);
        //最后只取值gc123即可
        //return topographicIndexFileName;
    }
    //查看任务是否保存过模型数据 如果没保存保存，保存则更新
    private void saveOrUpdateModelData(String taskId,String teraVersion,String dmslId){
        String userId = PlatformSessionContext.getUserID();
        //获取当前的是否是层次分析法的最终结果
        //DzzhModelSandLiquefaction result = sandLiquefactionRepository.getModelSandLiquefaction1(taskId, ResultEnum.FINA.getState() + "", "3");
        DzzhModelSandLiquefaction result = sandLiquefactionRepository.getByDmslId(dmslId);
        if(PlatformObjectUtils.isEmpty(result)){
            //如果不是当前任务关于层次分析的最终模型 删除并新增
            sandLiquefactionRepository.delFinalResultByTaskId(taskId,userId);
            //String dmslId = UUIDGenerator.getUUID();
            DzzhModelSandLiquefaction modelSandLiquefaction = new DzzhModelSandLiquefaction();
            modelSandLiquefaction.setDmslId(dmslId).setTaskId(taskId)
                    .setLithologyVersion("").setAlgorithmType("3")
                    .setAltitudeVersion(teraVersion).setA1Version("").setA2Version("").setA3Version("")
                    .setOperands("3").setResultStatus(ResultEnum.FINA.getState() + "");
            modelSandLiquefaction.setEvaluateUser(userId);
            modelSandLiquefaction.setEvaluateTime(new Date());
            String user = sUserService.getSUser(userId);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            modelSandLiquefaction.setEvaluateUserName(sUser.getUserName());
            modelSandLiquefaction.setCreateUser(userId);
            modelSandLiquefaction.setCreateTime(new Date());
            modelSandLiquefaction.setDelFlag(YNEnum.N.toString());
            modelSandLiquefaction.setSelectedMatrix(1);
            sandLiquefactionRepository.saveFinalResult(modelSandLiquefaction);
        }else{
            //如果是当前任务关于层次分析的最终模型  更新高程版本数据
            sandLiquefactionRepository.updateGcVersion(result.getDmslId(),teraVersion);
        }
    }


    //保存或恒信生成的综合地形指数的文件信息
    private void saveIndexFile(String taskId,String fileName1,String fileName2,String cutedGcFileName,String dmslId){
        //查询
        OmprehensiveTerrainIndexAndSite obj = sandLiquefactionRepository.getOmprehensiveTerrainIndexAndSite(taskId,dmslId);
        if(obj==null){
            //保存
            sandLiquefactionRepository.save(UUIDGenerator.getUUID(),taskId,fileName1,fileName2,cutedGcFileName,dmslId);
        }else{
            //更新
            sandLiquefactionRepository.update(obj.getDdtisId(),fileName1,fileName2,cutedGcFileName);
        }
    }
    @Override
    public void calculateSite(String teraVersion,String taskId,Map<String,Object> map,String gcFileName,String dmslId) throws Exception {
        //获取裁剪后的高程文件
        String cutedGcFileName = cutGcFile(gcFileName,teraVersion,taskId);
        if("评估失败,裁剪高程数据失败".equals(cutedGcFileName)){
            throw new RuntimeException(cutedGcFileName);
        }
        map.put("gcFileName",cutedGcFileName);
        if (StringUtils.isBlank(dmslId)){
            dmslId = UUIDGenerator.getUUID();
        }
        if(StringUtils.isNotBlank(cutedGcFileName)){
            //获取场地类别-活动构造区
            String activeSiteName = getGridFile("demCdlbCount",cutedGcFileName,"1");
            //获取场地类别-稳定构造区
            String steadySiteName = getGridFile("demCdlbCount",cutedGcFileName,"2");
            if(StringUtils.isNotBlank(activeSiteName) && StringUtils.isNotBlank(steadySiteName)){
                saveIndexFile(taskId,activeSiteName,steadySiteName,cutedGcFileName,dmslId);
                map.put("fileName",Arrays.asList(activeSiteName,steadySiteName));
            }else{
                map.put("fileName",new ArrayList<>());
            }
        }else{
            map.put("fileName",new ArrayList<>());
        }
        //保存信息
        saveOrUpdateModelData(taskId,teraVersion,dmslId);
        map.put("dmslId",dmslId);
        //return Arrays.asList(activeSiteName,steadySiteName);
    }

    @Override
    public List<DzzhResultSandLiquefactionVO> getEvaluateResult(String dmslId,String taskDistrict,String taskId) {
        List<DzzhResultDetailSandLiquefaction> list = sandLiquefactionRepository.getResultDataById(dmslId);
        List<DzzhResultSandLiquefactionVO> vos = new ArrayList<>();
        if(PlatformObjectUtils.isNotEmpty(list)){
            //0.2,地下水位深度>0的集合
            Map<BigDecimal, List<DzzhResultDetailSandLiquefaction>> collect = list.stream().filter(dzzhResultDetailSandLiquefaction->{
                return dzzhResultDetailSandLiquefaction.getLiquefactionGroundWaterDepth().compareTo(BigDecimal.ZERO)>0;
            }).collect(Collectors.groupingBy(dzzhResultDetailSandLiquefaction -> dzzhResultDetailSandLiquefaction.getEarthquakeAcceleration()));
            collect.forEach((k,v)->{
                //根据钻孔编号进行去重
                List<DzzhResultDetailSandLiquefaction> distinctList = v.stream().collect(
                        Collectors.collectingAndThen(Collectors.toCollection(
                                () -> new TreeSet<>(Comparator.comparing(DzzhResultDetailSandLiquefaction::getDrillCode))), ArrayList::new)
                );
                Boolean canShowMapBtn = canShowMapBtn(distinctList, taskDistrict, taskId);
                String canShow = "0";
                 if(canShowMapBtn){
                     canShow = "1";
                 }
                DzzhResultSandLiquefactionVO vo = new DzzhResultSandLiquefactionVO();
                vo.setEarthquakeAcceleration(k);
                vo.setLiquefactionGroundWaterDepth("实际水位深度");
                vo.setCanShow(canShow);
                vos.add(vo);
                //当某个地震动加速度的地下水位深度有非0值时那么肯定存在0值。非零值中的钻孔及标贯点信息和0值的钻孔和标贯点信息完全一致
                //当非0值可以展示查看地图的按钮时，0值也满足此条件
                DzzhResultSandLiquefactionVO zeroVo = new DzzhResultSandLiquefactionVO();
                zeroVo.setEarthquakeAcceleration(k);
                zeroVo.setLiquefactionGroundWaterDepth("0");
                zeroVo.setCanShow(canShow);
                vos.add(zeroVo);
            });
        }
        return  vos.stream().sorted(Comparator.comparing(DzzhResultSandLiquefactionVO::getEarthquakeAcceleration)).collect(Collectors.toList());
    }
    private String getSysAreaByName(String areaData){
        String[] split = areaData.split("-");
        String province = "";
        String city = "";
        String area = "";
        if (split.length == 3) {
            province = split[0];
            city = split[1];
            area = split[2];
        } else if (split.length == 2) {
            province = split[0];
            if(PlatformObjectUtils.isNotEmpty(split[1])){
                if("北京市".equals(split[0]) || "上海市".equals(split[0]) || "重庆市".equals(split[0]) || "天津市".equals(split[0])){
                    area = split[1];
                    city = province;
                }
            }
        } else {
            province = split[0];
            city = "-1";
            area = "-1";
        }
        String jsonStr = sysAreaService.getSysAreaByName(province, city, area);
        return jsonStr;
    }
    private Boolean canShowMapBtn(List<DzzhResultDetailSandLiquefaction> distinctList,String taskDistrict,String taskId){
        String[] districts = taskDistrict.split("、");
        List<DzzhResultDetailSandLiquefaction> entityList = new ArrayList<>();
        if(districts.length>1){
            //表示不连续的两块区域
            for (String areaData : districts) {
                // 获取每个区域空间数据
                String[] split = areaData.split("-");
                String areaGeomText = "";
                //根据区域的省市县数据取表中查询对应的空间数据
                if (split.length == 3) {
                    areaGeomText = boundaryService.getGeomByArea(split[0], split[1], split[2]);
                } else if (split.length == 2) {
                    areaGeomText = boundaryService.getGeomByArea(split[0], split[1], "");
                } else {
                    areaGeomText = boundaryService.getGeomByArea(split[0], "", "");
                }
                for(DzzhResultDetailSandLiquefaction entity:distinctList){
                    if(PlatformObjectUtils.isNotEmpty(entity.getArea())){
                        continue;
                    }
                    BigDecimal longitude = entity.getLongitude();
                    BigDecimal latitude = entity.getLatitude();
                    //根据空间数据和经纬度判断是否相交
                    Boolean stIntersects = lawAnalysisRepository.getSTIntersects(areaGeomText, longitude, latitude);
                    if (stIntersects) {
                        // 相交，表示此钻孔是这个区域内的
                        entityList.add(entity);
                        entity.setArea(split[0]+split[1]+split[2]);
                    }
                }
                // ②目标区为不连续地块时，每个地块单元应至少布置两个控制性钻孔否则不展示或目标区仅为一个迪区块，且该地区块中只有一个钻孔也不展示
                if (entityList.size() < 2) {
                    return false;
                }
                //遍历循环距离当前钻孔的距离(// ①任务区域内控制性钻孔空间间隔（钻孔据离最近的一个钻孔距离）应不大于700m)
                for (DzzhResultDetailSandLiquefaction resultDetailSandLiquefaction : entityList) {
                    BigDecimal nearestDistince = null;
                    for (DzzhResultDetailSandLiquefaction entity : entityList) {
                        if(resultDetailSandLiquefaction.getDrslId().equals(entity.getDrslId())){
                            continue;
                        }
                        BigDecimal distance = sandLiquefactionRepository.getNearestDistanceByDrill( resultDetailSandLiquefaction.getLongitude(), resultDetailSandLiquefaction.getLatitude(),
                                entity.getLongitude(), entity.getLatitude());
                        if(nearestDistince==null || nearestDistince.compareTo(distance)>0){
                            nearestDistince = distance;
                        }
                    }
                    if(nearestDistince==null || nearestDistince.compareTo(BigDecimal.valueOf(700))>0){
                        return false;
                    }
                    // ①钻孔与目标区边界距离应不大于350m
                    BigDecimal nearestDistance = sandLiquefactionRepository.getNearestBoundaryDistance(resultDetailSandLiquefaction.getLongitude(), resultDetailSandLiquefaction.getLatitude(), taskId);
                    if (nearestDistance!=null && nearestDistance.compareTo(BigDecimal.valueOf(350)) > 0) {
                        // 不展示液化结果分布图的查看按钮
                        return false;
                    }
                }
            }
        }else if(districts.length==1){
            //一块区域
            //遍历循环距离当前钻孔的距离(// ①任务区域内控制性钻孔空间间隔（钻孔据离最近的一个钻孔距离）应不大于700m)
            for (DzzhResultDetailSandLiquefaction resultDetailSandLiquefaction : distinctList) {
                BigDecimal nearestDistince = null;
                for (DzzhResultDetailSandLiquefaction entity : distinctList) {
                    if(resultDetailSandLiquefaction.getDrslId().equals(entity.getDrslId())){
                        continue;
                    }
                    BigDecimal distance = sandLiquefactionRepository.getNearestDistanceByDrill( resultDetailSandLiquefaction.getLongitude(), resultDetailSandLiquefaction.getLatitude(),
                            entity.getLongitude(), entity.getLatitude());
                    if(nearestDistince==null || nearestDistince.compareTo(distance)>0){
                        nearestDistince = distance;
                    }
                }
                if(nearestDistince==null || nearestDistince.compareTo(BigDecimal.valueOf(700))>0){
                    return false;
                }
                // ①钻孔与目标区边界距离应不大于350m
                BigDecimal nearestDistance = sandLiquefactionRepository.getNearestBoundaryDistance(resultDetailSandLiquefaction.getLongitude(), resultDetailSandLiquefaction.getLatitude(), taskId);
                if (nearestDistance!=null && nearestDistance.compareTo(BigDecimal.valueOf(350)) > 0) {
                    // 不展示液化结果分布图的查看按钮
                    return false;
                }
            }
        }
//        for (String areaData : districts) {
//            // 获取每个区域空间数据
//            String[] split = areaData.split("-");
//            String areaGeomText = "";
//            //根据区域的省市县数据取表中查询对应的空间数据
//            if (split.length == 3) {
//                areaGeomText = boundaryService.getGeomByArea(split[0], split[1], split[2]);
//            } else if (split.length == 2) {
//                areaGeomText = boundaryService.getGeomByArea(split[0], split[1], "");
//            } else {
//                areaGeomText = boundaryService.getGeomByArea(split[0], "", "");
//            }
//            for(DzzhResultDetailSandLiquefaction entity:distinctList){
//                if(PlatformObjectUtils.isNotEmpty(entity.getArea())){
//                    continue;
//                }
//                BigDecimal longitude = entity.getLongitude();
//                BigDecimal latitude = entity.getLatitude();
//                //根据空间数据和经纬度判断是否相交
//                Boolean stIntersects = lawAnalysisRepository.getSTIntersects(areaGeomText, longitude, latitude);
//                if (stIntersects) {
//                    // 相交，表示此钻孔是这个区域内的
//                    entityList.add(entity);
//                    entity.setArea(split[0]+split[1]+split[2]);
//                }
//            }
//            // ②目标区为不连续地块时，每个地块单元应至少布置两个控制性钻孔否则不展示或目标区仅为一个迪区块，且该地区块中只有一个钻孔也不展示
//            if (entityList.size() < 2) {
//                return false;
//            }
//            //遍历循环距离当前钻孔的距离(// ①任务区域内控制性钻孔空间间隔（钻孔据离最近的一个钻孔距离）应不大于700m)
//            for (DzzhResultDetailSandLiquefaction resultDetailSandLiquefaction : entityList) {
//                BigDecimal nearestDistince = null;
//                for (DzzhResultDetailSandLiquefaction entity : entityList) {
//                    if(resultDetailSandLiquefaction.getDrslId().equals(entity.getDrslId())){
//                        continue;
//                    }
//                    BigDecimal distance = sandLiquefactionRepository.getNearestDistanceByDrill( resultDetailSandLiquefaction.getLongitude(), resultDetailSandLiquefaction.getLatitude(),
//                            entity.getLongitude(), entity.getLatitude());
//                    if(nearestDistince==null || nearestDistince.compareTo(distance)>0){
//                        nearestDistince = distance;
//                    }
//                }
//                if(nearestDistince==null || nearestDistince.compareTo(BigDecimal.valueOf(700))>0){
//                    return false;
//                }
//                // ①钻孔与目标区边界距离应不大于350m
//                BigDecimal nearestDistance = sandLiquefactionRepository.getNearestBoundaryDistance(resultDetailSandLiquefaction.getLongitude(), resultDetailSandLiquefaction.getLatitude(), taskId);
//                if (nearestDistance!=null && nearestDistance.compareTo(BigDecimal.valueOf(350)) > 0) {
//                    // 不展示液化结果分布图的查看按钮
//                    return false;
//                }
//            }
//        }
        return true;
    }
//    @Override
//    public List<DzzhResultSandLiquefactionVO> getEvaluateResult(String dmslId) {
//        List<DzzhResultSandLiquefaction> list = sandLiquefactionRepository.getDataById(dmslId);
//
//        List<DzzhResultSandLiquefactionVO> voList = new ArrayList<>();
//        List<DzzhResultSandLiquefactionVO> finalVoList = voList;
//        if (PlatformObjectUtils.isNotEmpty(list)) {
//            Map<BigDecimal, List<DzzhResultSandLiquefaction>> collect = list.stream().collect(Collectors.groupingBy(dzzhResultSandLiquefaction -> dzzhResultSandLiquefaction.getEarthquakeAcceleration()));
//            collect.forEach((k, v)->{
//                if(v.size()>0){
//                    DzzhResultSandLiquefactionVO vo = new DzzhResultSandLiquefactionVO();
//                    vo.setEarthquakeAcceleration(k);
//                    vo.setLiquefactionGroundWaterDepth("实际水位深度");
//                    finalVoList.add(vo);
//                }
//                DzzhResultSandLiquefactionVO vo = new DzzhResultSandLiquefactionVO();
//                vo.setEarthquakeAcceleration(k);
//                vo.setLiquefactionGroundWaterDepth("0");
//                finalVoList.add(vo);
//            });
//            DzzhModelSandLiquefaction modelSandLiquefaction = sandLiquefactionRepository.getModelSandLiquefaction("", dmslId, "2");
//            if (PlatformObjectUtils.isNotEmpty(modelSandLiquefaction)) {
//                String algorithmType = modelSandLiquefaction.getAlgorithmType();
//                String operands = modelSandLiquefaction.getOperands();
//                //只有标贯法的饱和砂土和粉土才会设置按钮可不可看 （控制评估结果的地图查看按钮可不可看）
//                if (algorithmType.equals(SandLiqueFactionEnum.SPT.getState() + "") && operands.equals(OperandsEnum.SANDSILT.getState() + "")) {
//                    finalVoList.forEach(entity -> {
//                        entity.setCanShow(modelSandLiquefaction.getCanShow());
//                    });
//                }
//            }
//            voList = finalVoList.stream().sorted(Comparator.comparing(DzzhResultSandLiquefactionVO::getEarthquakeAcceleration)).collect(Collectors.toList());
//        }
//        return voList;
//    }

    @Override
    public void export(String dmslId, Double earthquakeAcceleration, Double groundWaterDepth, String flag, HttpServletResponse response) {
        List<StandardPenetrationVO> details = null;
        //按照钻孔编号、经度、纬度分组
        Map<String, List<StandardPenetrationVO>> standardCollect = new HashMap<>();
        List<AhpVO> ahp = null;
        Map<String, List<AhpVO>> ahpCollect = new HashMap<>();
        if ("1".equals(flag)) {
            details = sandLiquefactionRepository.getStandardPenetration(dmslId, earthquakeAcceleration, groundWaterDepth);
            standardCollect = details.stream().collect(Collectors.groupingBy(entity -> {
                return entity.getDrillCode() + "_" + entity.getLongitude() + "_" + entity.getLatitude();
            }));
        } else {
            ahp = sandLiquefactionRepository.getAhp(dmslId, earthquakeAcceleration, groundWaterDepth);
            ahpCollect = ahp.stream().collect(Collectors.groupingBy(entity -> {
                return entity.getDrillCode() + "_" + entity.getLongitude() + "_" + entity.getLatitude();
            }));
        }

        //创建工作簿
        XSSFWorkbook wb = new XSSFWorkbook();
        //创建sheet页
        XSSFSheet sheet = wb.createSheet("评估详情");
        //获取标题数组
        String[] tital = getTital(flag);
        //标题行样式
        XSSFCellStyle titalCellStyle = getTitalCellStyle(wb);
        //数据行行样式
        XSSFCellStyle bodyCellStyle = getBodyCellStyle(wb);
        //设置标题行
        XSSFRow row = sheet.createRow(0);
        //每行单元格的数量
        int cellLength = tital.length;
        //创建标题单元格并设置标题
        for (int i = 0; i < cellLength; i++) {
            XSSFCell cell = row.createCell(i);
            String cellValueStr = tital[i];
            cell.setCellValue(new XSSFRichTextString(cellValueStr));
            sheet.setColumnWidth(i, cellValueStr.getBytes().length * 256);
            cell.setCellStyle(titalCellStyle);
        }

        //数据行的起始行
        AtomicInteger dataStartRow = new AtomicInteger(1);
        //要合并的起始行 初始值为0
        final int[] mergeStratIndex = {0};
        //创建数据行
        if ("1".equals(flag)) {
            standardCollect.forEach((k, v) -> {
                int size = v.size();
                for (int i = 0; i < size; i++) {
                    //创建行
                    XSSFRow newRow = sheet.createRow(dataStartRow.get());
                    for (int j = 0; j < cellLength; j++) {
                        //创建单元格
                        XSSFCell cell = newRow.createCell(j);
                        //设置单元格样式
                        cell.setCellStyle(bodyCellStyle);
                        StandardPenetrationVO vo = v.get(i);
                        //通过反射的方式将实体属性对应的数据到每一个单元格内
                        Field[] fields = vo.getClass().getDeclaredFields();
                        if (PlatformObjectUtils.isNotEmpty(fields)) {
                            fields[j].setAccessible(true);
                            Field field = fields[j];
                            String fieldName = field.getName();
                            try {
                                Object value = field.get(vo);
                                if("liquefactionDifferentiate".equals(fieldName)){
                                    if(PlatformObjectUtils.isNotEmpty(value) && "0".equals(value)){
                                        value = "不液化";
                                    }else  if(PlatformObjectUtils.isNotEmpty(value) && "1".equals(value)){
                                        value = "液化";
                                    }
                                }
                                if("drillLiquefactionDifferentiate".equals(fieldName)){
                                    if(PlatformObjectUtils.isNotEmpty(value) && "0".equals(value)){
                                        value = "不液化";
                                    }else  if(PlatformObjectUtils.isNotEmpty(value) && "1".equals(value)){
                                        value = "液化";
                                    }
                                }
                                cell.setCellValue(new XSSFRichTextString(PlatformObjectUtils.isNotEmpty(value) ? value.toString() : ""));
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    dataStartRow.getAndIncrement();
                }

                //合并单元格
                if (size > 1) {
                    sheet.addMergedRegion(new CellRangeAddress(mergeStratIndex[0] + 1, mergeStratIndex[0] + size, 0, 0));
                    sheet.addMergedRegion(new CellRangeAddress(mergeStratIndex[0] + 1, mergeStratIndex[0] + size, 1, 1));
                    sheet.addMergedRegion(new CellRangeAddress(mergeStratIndex[0] + 1, mergeStratIndex[0] + size, 2, 2));
                    sheet.addMergedRegion(new CellRangeAddress(mergeStratIndex[0] + 1, mergeStratIndex[0] + size, 17, 17));
                }
                mergeStratIndex[0] = (mergeStratIndex[0] + size);
            });
        } else {
            ahpCollect.forEach((k, v) -> {
                int size = v.size();
                for (int i = 0; i < size; i++) {
                    //创建行
                    XSSFRow newRow = sheet.createRow(dataStartRow.get());
                    for (int j = 0; j < cellLength; j++) {
                        //创建单元格
                        XSSFCell cell = newRow.createCell(j);
                        //设置单元格样式
                        cell.setCellStyle(bodyCellStyle);
                        AhpVO vo = v.get(i);
                        //通过反射的方式将实体属性对应的数据到每一个单元格内
                        Field[] fields = vo.getClass().getDeclaredFields();
                        if (PlatformObjectUtils.isNotEmpty(fields)) {
                            fields[j].setAccessible(true);
                            Field field = fields[j];
                            try {
                                Object value = field.get(vo);
                                cell.setCellValue(new XSSFRichTextString(PlatformObjectUtils.isNotEmpty(value) ? value.toString() : ""));
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    dataStartRow.getAndIncrement();
                }

                //合并单元格
                if (size > 1) {
                    sheet.addMergedRegion(new CellRangeAddress(mergeStratIndex[0] + 1, mergeStratIndex[0] + size, 0, 0));
                    sheet.addMergedRegion(new CellRangeAddress(mergeStratIndex[0] + 1, mergeStratIndex[0] + size, 1, 1));
                    sheet.addMergedRegion(new CellRangeAddress(mergeStratIndex[0] + 1, mergeStratIndex[0] + size, 2, 2));
                    sheet.addMergedRegion(new CellRangeAddress(mergeStratIndex[0] + 1, mergeStratIndex[0] + size, 21, 21));
                }
                mergeStratIndex[0] = (mergeStratIndex[0] + size);
            });
        }

        OutputStream osOut = null;
        try {

            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("评估详情" + ".xlsx", "UTF-8"));
            response.setContentType("application/octet-stream;charset=UTF-8");
            osOut = response.getOutputStream();
            wb.write(osOut);
            osOut.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (osOut != null) {
                    osOut.close();
                }
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    private String[] getTital(String flag) {
        String[] tital = new String[]{"钻孔编号", "钻孔经度（°）", "钻孔纬度（°）", "液化判别地下水位深度dw(m)", "调整系数（β）",
                "地层编号", "层底深度", "分层厚度", "土层名称", "标贯点顶深（m）", "标贯点底深（m）", "标贯点深度ds(m)", "黏粒含量ρc（%）",
                "实际锤击数N（击）", "标准贯人锤击数临界值(击)", "N/NCR比值", "液化判别", "钻孔液化判别"
        };

        //1表示标贯法 2表示液化指数法
        if ("2".equals(flag)) {
            tital = new String[]{"钻孔编号", "钻孔经度（°）", "钻孔纬度（°）", "液化判别地下水位深度dw(m)", "调整系数（β）",
                    "地层编号", "层底深度", "分层厚度", "土层名称", "标贯点顶深（m）", "标贯点底深（m）", "标贯点深度ds(m)", "标贯点所代表土层的中点深度hi中点（m）",
                    "标贯点代表的土层厚度di（m）", "黏粒含量ρc（%）", "实际锤击数N（击）", "标准贯人锤击数临界值(击)", "N/NCR比值", "液化判别", "wi值", "液化指数",
                    "钻孔液化指数"
            };
        }
        return tital;
    }

    private XSSFCellStyle getTitalCellStyle(XSSFWorkbook wb) {
        XSSFCellStyle titalCellStyle = wb.createCellStyle();
        titalCellStyle.setAlignment(HorizontalAlignment.CENTER);//设置水平居中
        titalCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//设置垂直居中
        titalCellStyle.getFont().setBold(true);
        titalCellStyle.getFont().setFontHeightInPoints((short) 25);
        titalCellStyle.setBorderLeft(BorderStyle.THIN);
        titalCellStyle.setBorderTop(BorderStyle.THIN);
        titalCellStyle.setBorderRight(BorderStyle.THIN);
        titalCellStyle.setBorderBottom(BorderStyle.THIN);
        return titalCellStyle;
    }

    private XSSFCellStyle getBodyCellStyle(XSSFWorkbook wb) {
        XSSFCellStyle bodyCellStyle = wb.createCellStyle();
        bodyCellStyle.setAlignment(HorizontalAlignment.CENTER);//设置水平居中
        bodyCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//设置垂直居中
        bodyCellStyle.getFont().setBold(false);
        bodyCellStyle.getFont().setFontHeightInPoints((short) 18);
        bodyCellStyle.setBorderLeft(BorderStyle.THIN);
        bodyCellStyle.setBorderBottom(BorderStyle.THIN);
        bodyCellStyle.setBorderRight(BorderStyle.THIN);
        return bodyCellStyle;
    }

    public static void main(String[] args) {
        int count = 12000;
        for(int ii=1; ii<=count;ii+=5000){
            int from = ii;
            int end = ii-1+5000;
            System.out.println("开始是"+from+"，结束时"+(from-1+5000));
        }
    }

    //按省统计危险性面积（【砂土液化-层次分析法】）
    @Override
    public RestResponse countResultAreaByProvince(String taskId) {
        if (PlatformObjectUtils.isEmpty(taskId)) {
            return RestResponse.fail("按省统计危险性面积失败！");
        }
        String modelType = "砂土液化-层次分析法";//模型类型
        String countType = "0";//按省统计
        String currTime = System.currentTimeMillis() + "";
        String districtLayerName = "district_boundary_province";//省行政区划表
        List<DistrictBoundary> districtBoundaryList = new ArrayList<>();//省行政区划列表
        String sqlFilter = "";
        List<String> provinceList = new ArrayList<>();
        //查询任务区域
        String sql01 = "select task_district,task_name from dzzh_task where dt_id=?";
        TaskEntity taskEntity = jdbcTemplate.queryForObject(sql01, new BeanPropertyRowMapper<>(TaskEntity.class), taskId);
        String taskDistrict = taskEntity.getTaskDistrict();
        //大屏任务标识1：是大屏任务；0：不是大屏任务
        String dpFlag = "0";
        String taskName = taskEntity.getTaskName();
        if(taskName.contains("大屏展示")){
            dpFlag = "1";
        }
        String[] tempArr = taskDistrict.split(",");
        for (int i = 0; i < tempArr.length; i++) {
            if (PlatformObjectUtils.isNotEmpty(tempArr[i])) {
                String province = tempArr[i].split("-")[0];
                provinceList.add(province);
            }
        }
        if (provinceList.size() > 0) {//应获取全省的市
            for (int i = 0; i < provinceList.size(); i++) {
                String province = provinceList.get(i);
                if (sqlFilter!="") {
                    sqlFilter += " or ";
                }
                sqlFilter += "name='" + province + "'";
            }
            //查询省行政区划编码
            String sql = "select code as divisionCode,name as province from district_boundary_province where " + sqlFilter;
            districtBoundaryList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(DistrictBoundary.class));
        }

        //行政区划查询
        String resultLayerName_0 = "temp_行政区划_" + currTime;//计算结果数据集名称
        Map<String, Object> map0 = new HashMap<>();
        map0.put("type", "矢量过滤查询dzzhcount");
        map0.put("layerName", districtLayerName);//矢量数据集名
        map0.put("resultLayerName", resultLayerName_0);//结果数据集名称
        map0.put("sqlFilter", sqlFilter);//SQL查询表达式
        RestResponse serverToken0 = hypergraphService.getServerToken(map0);
        if (serverToken0.getCode() != 200) {
            return serverToken0;
        }
        DzzhModelSandLiquefaction modelSandLiquefaction = sandLiquefactionRepository.getModelSandLiquefaction(taskId, ResultEnum.FINA.getState() + "");
        if (PlatformObjectUtils.isNotEmpty(modelSandLiquefaction)) {
            String modelId = modelSandLiquefaction.getDmslId();//模型ID
            //任务ID删除省统计危险性面积结果
            eqLandslideService.deleteDzzhCountAreaResultByTaskId(taskId,countType,modelId);
            List<AhpResultEntity> list = sandLiquefactionRepository.getAhpResultListByTaskId(modelId,taskId);
            if(list.size()>0){
                for (int i = 0; i < list.size(); i++) {
                    String layerName = list.get(i).getFilePath();//砂土液化层次分析法计算结果图层名
                    String intensity = list.get(i).getPlaceType();//场地类别：活动构造区，稳定大陆区
                    String pga = list.get(i).getPga();//pga：50年超越概率2%、50年超越概率10%、50年超越概率63%
                    if(intensity.equals("活动构造区")){
                        intensity = "0";
                    }else if(intensity.equals("稳定大陆区")){
                        intensity = "1";
                    }
                    //pga：0: 50年超越概率2%、1: 50年超越概率10%、2: 50年超越概率63%
                    if(pga.equals("50年超越概率2%")){
                        pga = "0";
                    }else if(pga.equals("50年超越概率10%")){
                        pga = "1";
                    }else if(pga.equals("50年超越概率63%")){
                        pga = "2";
                    }
                    //计算结果重分级数据集名
                    String resultLayerName = layerName.replace("重分类","重分级");//final_重分类_自然分割_1702464581288
                    //查询重分级数据集表名
                    RestResponse serverToken1 = hypergraphService.getDatasetInfoByDataset(resultLayerName);
                    if (serverToken1.getCode() != 200) {
                        //栅格计算重分级
                        String countString = "Con([dzzhTifCount." + layerName + "]==-9999,-9999," +
                                "Con([dzzhTifCount." + layerName + "]==0,0," +
                                "Con([dzzhTifCount." + layerName + "]==1,1," +
                                "Con([dzzhTifCount." + layerName + "]==2,2," +
                                "Con([dzzhTifCount." + layerName + "]==3,3,4)))))";
                        Map<String, Object> map2 = new HashMap<>();
                        map2.put("type", "栅格计算重分级");
                        map2.put("layerName", layerName);//栅格数据集名称
                        map2.put("countString", countString);//栅格计算表达式
                        map2.put("resultLayerName", resultLayerName);//计算结果数据集名称
                        RestResponse serverToken2 = hypergraphService.getServerToken(map2);
                        if (serverToken2.getCode() != 200) {
                            return serverToken2;
                        }
                    }
                    //按省/市统计危险性面积（【砂土液化-层次分析法】）
                    countAhpResultGridArea(currTime, intensity ,resultLayerName,countType,resultLayerName_0,districtBoundaryList,taskId,dpFlag,modelId,pga);
                }
            }
        }

        return RestResponse.succeed(null);
    }

    //按省/市统计危险性面积（【砂土液化-层次分析法】）
    public RestResponse countAhpResultGridArea(String currTime, String intensity, String layerName, String countType, String districtLayerName,
                                          List<DistrictBoundary> districtBoundaryList, String taskId, String dpFlag, String modelId, String pga){
        //区域制表统计栅格分级面积
        Map<String, Object> map1 = new HashMap<>();
        map1.put("type", "区域制表统计栅格分级面积");//面积单位：万平方公里
        map1.put("layerName", layerName);
        map1.put("districtLayerName", districtLayerName);
        String resultLayerName1 = "temp_ahpr_table_" + currTime + "_" + intensity;//裁剪结果数据集
        map1.put("resultLayerName", resultLayerName1);
        RestResponse serverToken1 = hypergraphService.getServerToken(map1);
        if (serverToken1.getCode() != 200) {
            return serverToken1;
        }

        List<DzzhCountAreaResult> dzzhCountAreaResultList = new ArrayList<>();
        //查询字段列表
        String sql1 = "SELECT column_name FROM information_schema.columns WHERE table_name = '"+resultLayerName1+"';";
        List<String> columnList = jdbcTemplate.queryForList(sql1, String.class);
        //查询结果列表
        String sql2 = "select value from "+resultLayerName1+" order by value";
        List<Integer> valueList = jdbcTemplate.queryForList(sql2, Integer.class);
        if(valueList!=null && valueList.size()>0){
            for(Integer value : valueList){
                //遍历行政区划区域数据
                for(DistrictBoundary districtBoundary : districtBoundaryList){
                    String code = districtBoundary.getDivisionCode();
                    String valueCode = "value_" + code;
                    for(String column : columnList){
                        if(column.equals(valueCode)){
                            //查询面积（平方公里）、占比（%）
                            String sql3 = "select b.code,b.name,a.value as gridvalue,a."+valueCode+"*10000 as area,CAST(b.area AS DECIMAL) / 1000000 as total_area,a."+valueCode+"*10000/(CAST(b.area AS DECIMAL) / 1000000) * 100 as percent " +
                                    "from "+resultLayerName1+" a,s_area b " +
                                    "where a.value = "+value+" and b.code='"+code+"'";//s_area表面积字段单位（平方米）
                            List<DzzhCountAreaResult> dzzhCountAreaResultList1 = jdbcTemplate.query(sql3, new BeanPropertyRowMapper<>(DzzhCountAreaResult.class));
                            for (int m = 0; m < dzzhCountAreaResultList1.size(); m++) {
                                DzzhCountAreaResult dzzhCountAreaResult = dzzhCountAreaResultList1.get(m);
                                String uuid = UUIDGenerator.getUUID();
                                dzzhCountAreaResult.setId(uuid);
                                dzzhCountAreaResult.setTaskId(taskId);
                                dzzhCountAreaResult.setModelType("砂土液化-层次分析法");//模型类型
                                dzzhCountAreaResult.setDpFlag(dpFlag);//大屏任务标识1：是大屏任务；0：不是大屏任务
                                dzzhCountAreaResult.setDzIntensity(intensity);//场地类别：0活动构造区，1稳定大陆区
                                dzzhCountAreaResult.setLayerName(layerName);//图层名称
                                dzzhCountAreaResult.setType(countType);//统计方式：0省 1市
                                dzzhCountAreaResult.setModelId(modelId);//模型ID
                                dzzhCountAreaResult.setExtend1(pga);//pga：0 50年超越概率2%、1 50年超越概率10%、2 50年超越概率63%
                                dzzhCountAreaResultList.add(dzzhCountAreaResult);
                            }
                            break;
                        }
                    }
                }
            }
        }
        //保存统计危险性面积结果
        eqLandslideService.saveDzzhCountAreaResultList(dzzhCountAreaResultList);
        //删除临时区域面积计算结果表
        jdbcTemplate.update("drop table "+resultLayerName1);

        return RestResponse.succeed(null);
    }

    @Override
    public RestResponse countResultAreaByCounty(String taskId) {
        if (PlatformObjectUtils.isEmpty(taskId)) {
            return RestResponse.fail("按区县统计危险性面积失败！");
        }
        String modelType = "砂土液化-层次分析法";//模型类型
        String countType = "1";//按市统计
        String currTime = System.currentTimeMillis() + "";
        String districtLayerName = "district_boundary_county";//市行政区划表
        List<DistrictBoundary> districtBoundaryList = new ArrayList<>();//市行政区划列表
        String sqlFilter = "";
        //查询任务区域
        String sql01 = "select task_district,task_name from dzzh_task where dt_id=?";
        TaskEntity taskEntity = jdbcTemplate.queryForObject(sql01, new BeanPropertyRowMapper<>(TaskEntity.class), taskId);
        String taskDistrict = taskEntity.getTaskDistrict();
        //大屏任务标识1：是大屏任务；0：不是大屏任务
        String dpFlag = "0";
        String taskName = taskEntity.getTaskName();
        if(taskName.contains("大屏展示")){
            dpFlag = "1";
        }
        String[] tempArr = taskDistrict.split(",");
        List<String> provinceList = new ArrayList<>();
        List<String> cityList = new ArrayList<>();
        for (int i = 0; i < tempArr.length; i++) {
            String[] tempStrArr = tempArr[i].split("-");
            if(tempStrArr.length > 2){
                //四川省-成都市-邛崃市
                String province = tempStrArr[0];
                String city = tempStrArr[1];
                String county = tempStrArr[2];
                if (sqlFilter != "") {
                    sqlFilter += " or ";
                }
                String sql0 = "select c.code from district_boundary_province a,district_boundary_city b,district_boundary_county c " +
                        "where a.name='" + province + "' and b.name='" + city + "' and c.name='" + county + "' and subString(a.code,1,2) = subString(b.code,1,2) and subString(b.code,1,4) = subString(c.code,1,4)";
                List<String> codeList = jdbcTemplate.queryForList(sql0, String.class);
                if (PlatformObjectUtils.isNotEmpty(codeList) && codeList.size() > 0) {
                    String cityCode = codeList.get(0);
                    sqlFilter += "code='" + cityCode + "'";
                }
            }else if (tempStrArr.length > 1) {
                //辽宁省-大连市
                String province = tempStrArr[0];
                String city = tempStrArr[1];
                cityList.add(province+"_"+city);
            } else {
                String province = tempStrArr[0];
                //辽宁省
                if (PlatformObjectUtils.isNotEmpty(province)) {
                    provinceList.add(province);
                }
            }
        }
        if(cityList.size()>0){
            //获取每个市的区县
            String sql = "select subString(code,1,4) as code from district_boundary_city where 1=1 ";
            int i = 0;
            for (; i < cityList.size(); i++) {
                String area = cityList.get(i);
                //查询省code的前两位
                String subSql = "select subString(code,1,2) as code from district_boundary_province where name = '"+area.split("_")[0]+"'";
                List<String> codeList = jdbcTemplate.queryForList(subSql, String.class);
                String provinceCode = "";
                if (PlatformObjectUtils.isNotEmpty(codeList) && codeList.size() > 0) {
                    provinceCode = codeList.get(0);
                }
                if (i > 0) {
                    sql += " or ";
                }
                if(StringUtils.isNotBlank(provinceCode)){
                    sql+=" and  (name='"+area.split("_")[1]+"' and code like '" + provinceCode + "%')";
                }else{
                    sql+=" and  (name='"+area.split("_")[1]+"')";
                }
            }
            if(i>0){
                //市code
                List<String> codeList = jdbcTemplate.queryForList(sql, String.class);
                if (PlatformObjectUtils.isNotEmpty(codeList) && codeList.size() > 0) {
                    for (int j = 0; j < codeList.size(); j++) {
                        String code = codeList.get(j);//行政区划编码前4位
                        if (sqlFilter != "") {
                            sqlFilter += " or ";
                        }
                        sqlFilter += "code like '" + code + "%'";
                    }
                }
            }
        }
        if (provinceList.size() > 0) {//应获取全省的市
            String provinceStr = "";
            for (int i = 0; i < provinceList.size(); i++) {
                String province = provinceList.get(i);
                if (i > 0) {
                    provinceStr += ",";
                }
                provinceStr += "'" + province + "'";
            }
            //查询省行政区划编码前2位
            String sql = "select subString(code,1,2) as code from district_boundary_province where name in (" + provinceStr + ")";
            List<String> codeList = jdbcTemplate.queryForList(sql, String.class);
            if (PlatformObjectUtils.isNotEmpty(codeList) && codeList.size() > 0) {
                for (int i = 0; i < codeList.size(); i++) {
                    String code = codeList.get(i);//行政区划编码前2位
                    if (sqlFilter != "") {
                        sqlFilter += " or ";
                    }
                    sqlFilter += "code like '" + code + "%'";
                }
            }
        }
        //查询区县行政区划列表
        String sql1 = "select code as divisionCode,name as city from district_boundary_county where " + sqlFilter;
        //区县code集合
        districtBoundaryList = jdbcTemplate.query(sql1, new BeanPropertyRowMapper<>(DistrictBoundary.class));
        //行政区划查询
        String resultLayerName_0 = "temp_行政区划_" + currTime;//计算结果数据集名称
        Map<String, Object> map0 = new HashMap<>();
        map0.put("type", "矢量过滤查询dzzhcount");
        map0.put("layerName", districtLayerName);//矢量数据集名
        map0.put("resultLayerName", resultLayerName_0);//结果数据集名称
        map0.put("sqlFilter", sqlFilter);//SQL查询表达式
        RestResponse serverToken0 = hypergraphService.getServerToken(map0);
        if (serverToken0.getCode() != 200) {
            return serverToken0;
        }
        DzzhModelSandLiquefaction modelSandLiquefaction = sandLiquefactionRepository.getModelSandLiquefaction(taskId, ResultEnum.FINA.getState() + "");
        if (PlatformObjectUtils.isNotEmpty(modelSandLiquefaction)) {
            String modelId = modelSandLiquefaction.getDmslId();//模型ID
            //任务ID删除省统计危险性面积结果
            eqLandslideService.deleteDzzhCountAreaResultByTaskId(taskId,countType,modelId);
            List<AhpResultEntity> list = sandLiquefactionRepository.getAhpResultListByTaskId(modelId,taskId);
            if(list.size()>0){
                for (int i = 0; i < list.size(); i++) {
                    String layerName = list.get(i).getFilePath();//砂土液化层次分析法计算结果图层名
                    String intensity = list.get(i).getPlaceType();//场地类别：活动构造区，稳定大陆区
                    String pga = list.get(i).getPga();//pga：50年超越概率2%、50年超越概率10%、50年超越概率63%
                    if(intensity.equals("活动构造区")){
                        intensity = "0";
                    }else if(intensity.equals("稳定大陆区")){
                        intensity = "1";
                    }
                    if(pga.equals("50年超越概率2%")){
                        pga = "0";
                    }else if(pga.equals("50年超越概率10%")){
                        pga = "1";
                    }else if(pga.equals("50年超越概率63%")){
                        pga = "2";
                    }
                    //计算结果重分级数据集名
                    String resultLayerName = layerName.replace("重分类","重分级");//final_重分类_自然分割_1702464581288
                    //查询重分级数据集表名
                    RestResponse serverToken1 = hypergraphService.getDatasetInfoByDataset(resultLayerName);
                    if (serverToken1.getCode() != 200) {
                        //栅格计算重分级
                        String countString = "Con([dzzhTifCount." + layerName + "]==-9999,-9999," +
                                "Con([dzzhTifCount." + layerName + "]==0,0," +
                                "Con([dzzhTifCount." + layerName + "]==1,1," +
                                "Con([dzzhTifCount." + layerName + "]==2,2," +
                                "Con([dzzhTifCount." + layerName + "]==3,3,4)))))";
                        Map<String, Object> map2 = new HashMap<>();
                        map2.put("type", "栅格计算重分级");
                        map2.put("layerName", layerName);//栅格数据集名称
                        map2.put("countString", countString);//栅格计算表达式
                        map2.put("resultLayerName", resultLayerName);//计算结果数据集名称
                        RestResponse serverToken2 = hypergraphService.getServerToken(map2);
                        if (serverToken2.getCode() != 200) {
                            return serverToken2;
                        }
                    }
                    //按省/市统计危险性面积（【砂土液化-层次分析法】）
                    countAhpResultGridArea(currTime, intensity ,resultLayerName,countType,resultLayerName_0,districtBoundaryList,taskId,dpFlag,modelId,pga);
                }
            }
        }

        return RestResponse.succeed(null);
    }

    //按市统计危险性面积（【砂土液化-层次分析法】分析评估结果）
    @Override
    public RestResponse countResultAreaByCity(String taskId) {
        if (PlatformObjectUtils.isEmpty(taskId)) {
            return RestResponse.fail("按市统计危险性面积失败！");
        }
        String modelType = "砂土液化-层次分析法";//模型类型
        String countType = "1";//按市统计
        String currTime = System.currentTimeMillis() + "";
        String districtLayerName = "district_boundary_city";//市行政区划表
        List<DistrictBoundary> districtBoundaryList = new ArrayList<>();//市行政区划列表
        String sqlFilter = "";
        //查询任务区域
        String sql01 = "select task_district,task_name from dzzh_task where dt_id=?";
        TaskEntity taskEntity = jdbcTemplate.queryForObject(sql01, new BeanPropertyRowMapper<>(TaskEntity.class), taskId);
        String taskDistrict = taskEntity.getTaskDistrict();
        //大屏任务标识1：是大屏任务；0：不是大屏任务
        String dpFlag = "0";
        String taskName = taskEntity.getTaskName();
        if(taskName.contains("大屏展示")){
            dpFlag = "1";
        }
        String[] tempArr = taskDistrict.split(",");
        List<String> provinceList = new ArrayList<>();
        for (int i = 0; i < tempArr.length; i++) {
            String[] tempStrArr = tempArr[i].split("-");
            if (tempStrArr.length > 1) {
                String province = tempStrArr[0];
                String city = tempStrArr[1];
                if (sqlFilter!="") {
                    sqlFilter += " or ";
                }
                String sql0 = "select b.code from district_boundary_province a,district_boundary_city b " +
                        "where a.name='"+province+"' and b.name='"+city+"' and subString(a.code,1,2) = subString(b.code,1,2)";
                List<String> codeList = jdbcTemplate.queryForList(sql0, String.class);
                if(codeList!=null && codeList.size()>0){
                    String cityCode = codeList.get(0);
                    sqlFilter += "code='" + cityCode + "'";
                }
            } else {
                String province = tempStrArr[0];
                if (PlatformObjectUtils.isNotEmpty(province)) {
                    provinceList.add(province);
                }
            }
        }
        if (provinceList.size() > 0) {//应获取全省的市
            String provinceStr = "";
            for (int i = 0; i < provinceList.size(); i++) {
                String province = provinceList.get(i);
                if (i > 0) {
                    provinceStr += ",";
                }
                provinceStr += "'" + province + "'";
            }
            //查询省行政区划编码前2位
            String sql = "select subString(code,1,2) as code from district_boundary_province where name in (" + provinceStr + ")";
            List<String> codeList = jdbcTemplate.queryForList(sql, String.class);
            if (codeList != null && codeList.size() > 0) {
                for (int i = 0; i < codeList.size(); i++) {
                    String code = codeList.get(i);//行政区划编码前2位
                    if (sqlFilter!="") {
                        sqlFilter += " or ";
                    }
                    sqlFilter += "code like '" + code + "%'";
                }
            }
        }
        //查询市行政区划列表
        String sql1 = "select code as divisionCode,name as city from district_boundary_city where " + sqlFilter;
        districtBoundaryList = jdbcTemplate.query(sql1, new BeanPropertyRowMapper<>(DistrictBoundary.class));
        //行政区划查询
        String resultLayerName_0 = "temp_行政区划_" + currTime;//计算结果数据集名称
        Map<String, Object> map0 = new HashMap<>();
        map0.put("type", "矢量过滤查询dzzhcount");
        map0.put("layerName", districtLayerName);//矢量数据集名
        map0.put("resultLayerName", resultLayerName_0);//结果数据集名称
        map0.put("sqlFilter", sqlFilter);//SQL查询表达式
        RestResponse serverToken0 = hypergraphService.getServerToken(map0);
        if (serverToken0.getCode() != 200) {
            return serverToken0;
        }
        DzzhModelSandLiquefaction modelSandLiquefaction = sandLiquefactionRepository.getModelSandLiquefaction(taskId, ResultEnum.FINA.getState() + "");
        if (PlatformObjectUtils.isNotEmpty(modelSandLiquefaction)) {
            String modelId = modelSandLiquefaction.getDmslId();//模型ID
            //任务ID删除省统计危险性面积结果
            eqLandslideService.deleteDzzhCountAreaResultByTaskId(taskId,countType,modelId);
            List<AhpResultEntity> list = sandLiquefactionRepository.getAhpResultListByTaskId(modelId,taskId);
            if(list.size()>0){
                for (int i = 0; i < list.size(); i++) {
                    String layerName = list.get(i).getFilePath();//砂土液化层次分析法计算结果图层名
                    String intensity = list.get(i).getPlaceType();//场地类别：活动构造区，稳定大陆区
                    String pga = list.get(i).getPga();//pga：50年超越概率2%、50年超越概率10%、50年超越概率63%
                    if(intensity.equals("活动构造区")){
                        intensity = "0";
                    }else if(intensity.equals("稳定大陆区")){
                        intensity = "1";
                    }
                    if(pga.equals("50年超越概率2%")){
                        pga = "0";
                    }else if(pga.equals("50年超越概率10%")){
                        pga = "1";
                    }else if(pga.equals("50年超越概率63%")){
                        pga = "2";
                    }
                    //计算结果重分级数据集名
                    String resultLayerName = layerName.replace("重分类","重分级");//final_重分类_自然分割_1702464581288
                    //查询重分级数据集表名
                    RestResponse serverToken1 = hypergraphService.getDatasetInfoByDataset(resultLayerName);
                    if (serverToken1.getCode() != 200) {
                        //栅格计算重分级
                        String countString = "Con([dzzhTifCount." + layerName + "]==-9999,-9999," +
                                "Con([dzzhTifCount." + layerName + "]==0,0," +
                                "Con([dzzhTifCount." + layerName + "]==1,1," +
                                "Con([dzzhTifCount." + layerName + "]==2,2," +
                                "Con([dzzhTifCount." + layerName + "]==3,3,4)))))";
                        Map<String, Object> map2 = new HashMap<>();
                        map2.put("type", "栅格计算重分级");
                        map2.put("layerName", layerName);//栅格数据集名称
                        map2.put("countString", countString);//栅格计算表达式
                        map2.put("resultLayerName", resultLayerName);//计算结果数据集名称
                        RestResponse serverToken2 = hypergraphService.getServerToken(map2);
                        if (serverToken2.getCode() != 200) {
                            return serverToken2;
                        }
                    }
                    //按省/市统计危险性面积（【砂土液化-层次分析法】）
                    countAhpResultGridArea(currTime, intensity ,resultLayerName,countType,resultLayerName_0,districtBoundaryList,taskId,dpFlag,modelId,pga);
                }
            }
        }

        return RestResponse.succeed(null);
    }

    @Override
    public String getMapResultFile(String taskId, String type,String dmslId) {
        DzzhDtis mapResult = sandLiquefactionRepository.getMapResultFile(taskId,dmslId);
        // 1:综合地形指数  2：场地类别-活动构造区 3：场地类别-稳定构造区
        if("1".equals(type)){
            return mapResult.getZhdxzs();
        }else if("2".equals(type)){
            return mapResult.getCdlb1();
        }
        return mapResult.getCdlb2();
    }

    @Override
    public String getFinalMapResultFile(String taskId, String dmslId, String landform, String pga) {
        if("2".equals(pga)){
            pga = "50年超越概率2%";
        }else if("10".equals(pga)){
            pga = "50年超越概率10%";
        }else if("63".equals(pga)){
            pga = "50年超越概率63%";
        }
        return sandLiquefactionRepository.getFinalMapResultFile(taskId,dmslId,landform,pga);
    }

    @Override
    public String handleRiver(Ahp ahp) throws Exception {
        Map<String, List<BigDecimal>> parameter = getRatio(ahp, ahp.getDmslId());
        TaskEntity taskEntity = taskService.viewTask(ahp.getTaskId());
        //水系
        String waterName= "";
        try {
            waterName = getAndBufferWater(taskEntity,parameter.get("距河流距离"));
        } catch (Exception e) {
            throw new RuntimeException("获取河流数据失败");
        }
        return waterName;
    }

    @Override
    public void deleteCountBuffer() {
        sandLiquefactionRepository.deleteByTaskId("");
    }


    @Override
    public DzzhModelResultVO getCenterResult(String taskId, String algorithmType, String dmslId) throws IllegalAccessException {
        //TaskEntity taskEntity = taskService.viewTask(taskId);
        TaskEntity taskEntity = taskService.getTaskWithOutGeom(taskId);
        DzzhModelResultVO vo = new DzzhModelResultVO();
        DzzhModelSandLiquefaction modelSandLiquefaction = sandLiquefactionRepository.getByDmslId(dmslId);
        if (PlatformObjectUtils.isEmpty(modelSandLiquefaction) || ObjectUtils.isEmpty(modelSandLiquefaction)) {
            modelSandLiquefaction = new DzzhModelSandLiquefaction();
            modelSandLiquefaction.setTaskNum(taskEntity.getTaskNum()).setDisasterType("砂土液化").setTaskDistrict(taskEntity.getTaskDistrict()).setTaskId(taskEntity.getDtId());
            String userID = PlatformSessionContext.getUserID();
            String user = sUserService.getSUser(userID);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            modelSandLiquefaction.setEvaluateUserName(sUser.getUserName());
            modelSandLiquefaction.setEvaluateUser(userID);
            vo.setModelSandLiquefaction(modelSandLiquefaction);
            vo.setResultSandLiquefaction(new ArrayList<>());
            return vo;
        } else {
            modelSandLiquefaction.setTaskNum(taskEntity.getTaskNum()).setDisasterType("砂土液化").setTaskDistrict(taskEntity.getTaskDistrict()).setTaskId(taskEntity.getDtId());
            vo.setModelSandLiquefaction(modelSandLiquefaction);
            if("3".equals(algorithmType)){
                AhpRatio ahpRatio = sandLiquefactionRepository.getAhpRatioData(taskId, modelSandLiquefaction.getDmslId());
                Ahp ahp = new Ahp();
                if (ahpRatio != null) {
                    String ratio = ahpRatio.getRatio();
                    JSONObject parse = (JSONObject) JSONObject.parse(ratio);
                    Field[] fields = ahp.getClass().getDeclaredFields();
                    if (PlatformObjectUtils.isNotEmpty(fields)) {
                        for (Field field : fields) {
                            field.setAccessible(true);
                            AddData annotation = field.getAnnotation(AddData.class);
                            if (annotation == null) {
                                continue;
                            }
                            String name = field.getName();
                            BigDecimal value = parse.getBigDecimal(name);
                            if (PlatformObjectUtils.isNotEmpty(value)) {
                                field.set(ahp, value);
                            }
                        }
                    }
                }
                //获取生成的超图文件
                OmprehensiveTerrainIndexAndSite dtis = sandLiquefactionRepository.getOmprehensiveTerrainIndexAndSite(taskId,dmslId);
                if(PlatformObjectUtils.isNotEmpty(dtis)){
                    if(StringUtils.isNotBlank(dtis.getZhdxzs())){
                        vo.getModelSandLiquefaction().setStatus1("1");
                        vo.getModelSandLiquefaction().setLandFormFileName(dtis.getZhdxzs());
                    }else{
                        vo.getModelSandLiquefaction().setStatus1("0");
                    }
                    if(StringUtils.isNotBlank(dtis.getCdlb1()) || StringUtils.isNotBlank(dtis.getCdlb2()) ){
                        vo.getModelSandLiquefaction().setStatus2("1");
                        List<String> siteFileName = new ArrayList<>(2);
                        if(StringUtils.isNotBlank(dtis.getCdlb1())){
                            siteFileName.add(dtis.getCdlb1());
                        }
                        if(StringUtils.isNotBlank(dtis.getCdlb2())){
                            siteFileName.add(dtis.getCdlb2());
                        }
                        vo.getModelSandLiquefaction().setSiteFileName(siteFileName);
                    }else{
                        vo.getModelSandLiquefaction().setStatus2("0");
                    }
                }
//                List<AhpResultEntity> ahpResultList = sandLiquefactionRepository.getAhpResultList(dmslId);
                List<AhpResultEntity> ahpResultList = sandLiquefactionRepository.getAhpResultListByTaskId(dmslId,taskId);
                if(PlatformObjectUtils.isNotEmpty(ahpResultList) && ahpResultList.size()>0){
                    vo.getModelSandLiquefaction().setStatus3("1");
                }else{
                    vo.getModelSandLiquefaction().setStatus3("0");
                }
                vo.setAhp(ahp);
            }else{
                List<DzzhResultSandLiquefaction> list = sandLiquefactionRepository.getDataById(modelSandLiquefaction.getDmslId());
                List<DzzhResultSandLiquefactionVO> voList = new ArrayList<>();
                if (PlatformObjectUtils.isNotEmpty(list)) {
                    Map<BigDecimal, List<DzzhResultSandLiquefaction>> collect = list.stream().collect(Collectors.groupingBy(dzzhResultSandLiquefaction -> dzzhResultSandLiquefaction.getEarthquakeAcceleration()));
                    List<DzzhResultSandLiquefactionVO> finalVoList = voList;
                    collect.forEach((k, v)->{
                        if(v.size()>0){
                            DzzhResultSandLiquefactionVO dzzhResultSandLiquefactionVO = new DzzhResultSandLiquefactionVO();
                            dzzhResultSandLiquefactionVO.setEarthquakeAcceleration(k);
                            dzzhResultSandLiquefactionVO.setLiquefactionGroundWaterDepth("实际水位深度");
                            dzzhResultSandLiquefactionVO.setCanShow("1");
                            finalVoList.add(dzzhResultSandLiquefactionVO);
                        }
                        DzzhResultSandLiquefactionVO dzzhResultSandLiquefactionVO = new DzzhResultSandLiquefactionVO();
                        dzzhResultSandLiquefactionVO.setEarthquakeAcceleration(k);
                        dzzhResultSandLiquefactionVO.setLiquefactionGroundWaterDepth("0");
                        dzzhResultSandLiquefactionVO.setCanShow("1");
                        finalVoList.add(dzzhResultSandLiquefactionVO);
                    });
                    voList = finalVoList.stream().sorted(Comparator.comparing(DzzhResultSandLiquefactionVO::getEarthquakeAcceleration)).collect(Collectors.toList());
                    vo.setResultSandLiquefaction(voList);
                }
                List<DzzhResultSandLiquefactionVO> evaluateResult = getEvaluateResult(modelSandLiquefaction.getDmslId(), taskEntity.getTaskDistrict(), taskId);
                vo.setResultSandLiquefaction(evaluateResult);
            }
        }

        return vo;
    }
}
